如何使用ajax和xml从自动完成搜索中将值放入隐藏字段

时间:2013-10-02 07:55:12

标签: javascript html ajax autocomplete

我在表单中使用以下脚本。我需要通过国家名称从xml文档获取内容,然后将genameId放入隐藏的文件中。 autocomplete seacrh工作正常,问题是如何将geonameId放入隐藏字段?

javascript:

<script type='text/javascript'> 
$(window).load(function(){

$.ajax({
 type: "GET",
 url: "Region.xml", // change to full path of file on server
 dataType: "xml",

success: function(xmlResponse) {
        var data = $("geoname", xmlResponse).map(function() {
            return {
                value: $("Name", this).text() ,
                id: $("geonameId", this).text()
            };
        }).get();
        $("#test").autocomplete({
            source: function(req, response) {
                var re = $.ui.autocomplete.escapeRegex(req.term);
                var matcher = new RegExp("^" + re, "i");
                response($.grep(data, function(item) {
                    return matcher.test(item.value);
                }));
            },
            minLength: 2,
            select: function(event, ui) {
                $("#result").html(ui.item ? ui.item.id : "Nothing selected, input was " + this.value);
            }
        });
    }
});
}); 

</script>

HTML:

<div class="ui-widget">

    <input id="test" />
</div>

<input type="hidden" name="result" value="">

如何将结果放入隐藏字段?

1 个答案:

答案 0 :(得分:1)

        $("#test").autocomplete({
            source: function(req, response) {
                var re = $.ui.autocomplete.escapeRegex(req.term);
                var matcher = new RegExp("^" + re, "i");
                response($.grep(data, function(item) {
                    return matcher.test(item.value);
                }));
            },
            minLength: 2,
            select: function(event, ui) {
                $("input[name='result']").val(ui.item ? ui.item.id : "Nothing selected, input was " + this.value);
            }
        });