Jquery val不为文本框设置新值

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

标签: php jquery jquery-ui jquery-autocomplete

我使用jqueryUI自动完成来搜索地理名称,但我无法将值设置为我的文本框 这是我的代码:

<script>
    $(function () {
        function log(message) {
            $("#appendedInputButton").val(message);
        }
        $("#appendedInputButton").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "http://ws.geonames.org/searchJSON",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function (data) {
                        response($.map(data.geonames, function (item) {
                            return {
                                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name
                            }
                        }));
                    }
                });
            },
            minLength: 1,
            select: function (event, ui) {
                log(ui.item ?
                    "Selected: " + ui.item.label :
                    "Nothing selected, input was " + this.value);
            },
            open: function () {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function () {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });
    });
</script>     

我的HTML是:

<div class="input-append">
    <form role="search" method="get" id="searchform" action="http://sushiant.com/">
        <button class="btn" type="submit" id="searchsubmit">جستجو</button>
        <input class="span2" name="appendedInputButton" id="appendedInputButton" size="16" type="text" style="width: 300px;">
    </form>
</div>

2 个答案:

答案 0 :(得分:1)

解决方案

用以下内容替换成功功能:

success: function (data) {
    response($.map(data.geonames, function (item) {
        var text = item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName;
        return {
            label: text,
            value: text
        }
    }));
}

我猜测"Selected: "部分仅用于调试目的,所以基本上你要做的是将labelvalue都设置为相同的字符串。

说明

val()的调用完全正常。您没有看到预期的结果,因为该值被value回调函数中设置的response字段覆盖,这是autocomplete的默认行为。

此外,永远不应该使用select未定义来调用ui.item事件,因为它会精确地对项目的选择作出反应......所以无论如何都不应该达到"Nothing selected, input was " + this.value);替代方案

答案 1 :(得分:-3)

尝试

$("#appendedInputButton").attr('value',message);
相关问题