Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

jquery - Autocomplete applying value not label to textbox

Im having troubles trying to get the autocomplete to work properly.

It all looks ok to me but....

<script>
$(function () {
    $("#customer-search").autocomplete({
        source: 'Customer/GetCustomerByName',
        minLength: 3,
        select: function (event, ui) {
            $("#customer-search").val(ui.item.label);
            $("#selected-customer").val(ui.item.label);
        }
    });
});
</script>
<div>
<input id="customer-search" />
 </div>
@Html.Hidden("selected-customer")

However when I select an item from the dropdown the value is been applied to the textbox instead of the label.

What have I done wrong?

If I look at the source using firebug I can see that my hidden field is being updated correctly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The default behavior of the select event is to update the input with ui.item.value. This code runs after your event handler.

Simply return false or call event.preventDefault() to prevent this from occurring. I would also recommend doing something similar for the focus event to prevent ui.item.value from being placed in the input as the user hovers over choices:

$("#customer-search").autocomplete({
    /* snip */
    select: function(event, ui) {
        event.preventDefault();
        $("#customer-search").val(ui.item.label);
        $("#selected-customer").val(ui.item.label);
    },
    focus: function(event, ui) {
        event.preventDefault();
        $("#customer-search").val(ui.item.label);
    }
});

Example: http://jsfiddle.net/andrewwhitaker/LCv8L/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...