jQuery autocomplete problem - doesn't match if user doesn't specifically select

早过忘川 提交于 2019-12-23 20:13:44

问题


Following on from my previous two questions:

How to make jQuery autocomplete execute a search() when user hits submit

How would I trim the input to a JQuery auto-complete box?

I have a jQuery UI 1.8 autocomplete box in my form, and for the most part it works like a charm. The one problem I have is that if I enter a valid name, but do not select the choice that appears, then the name is never matched against my {name,value} list and so the correct value for the hidden input that contains the 'value' part is not set. This of course causes the confusing situation where one can enter a name you know is correct, hit submit and be told you haven't entered a correct name (as the value is null).

How can I make sure that the hidden input value is set even if the user doesn't make a choice from the autocomplete box? Is there some function I can tie to the onclick event of the submit button which would make jQuery do a search with what is in the box and automatically select the first option? Alternatively, can I make it so that the autocomplete will select the first option when the user deselects the input box in any way (return/tab/click off/etc)?

Thanks.


回答1:


Here is my solution to your problem. I just added the part regarding the change event. I hope it helps.

jQuery(function(){
    jQuery('#Resource').autocomplete({
        source: data,
        focus: function(event, ui) {
            jQuery('#Resource').val(ui.item.label);
            return false;
        },          
        select: function(event, ui) {
            jQuery('#Resource').val(ui.item.label);
            jQuery('#EmployeeNumber').val(ui.item.value);
            return false;
        },
        change: function(event,ui){
                for (var i in data){
                    if (data[i].label==jQuery('#Resource').val()){
                        jQuery('#EmployeeNumber').val(data[i].value);
                    }
                }
        }
    });
}); 


来源:https://stackoverflow.com/questions/3317685/jquery-autocomplete-problem-doesnt-match-if-user-doesnt-specifically-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!