JQuery autocomplete problem - not appropriate unless user specifically selects

Following my previous two questions:

How to make jQuery autocomplete do a search () when user clicks submit

How would I crop input into a jQuery autocomplete window?

I have jQuery UI 1.8 autocomplete in my form, and for the most part it works like a charm. The only problem that arises for me is that if I enter a valid name, but don’t select the choice that appears , then the name is never matched to my list {name,value}, and therefore the correct value is for the hidden input that contains the “value” part , not installed. This, of course, causes a confusing situation when you can enter a name, which, as you know, is correct, click submit and inform that you did not specify the correct name (since the value null).

How can I make sure that the value of the hidden input is set even if the user does not make a choice from the autocomplete field? Is there any function that I can associate with the onclick event of the submit button that will force jQuery to search with what's in the field and automatically select the first option? Alternatively, can I make it so that autocomplete selects the first option when the user somehow deselects the input (return / tab / click off / etc)?

Thank.

+3
source share
1 answer

Here is my solution to your problem. I added only part of the change event . Hope this 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);
                    }
                }
        }
    });
}); 
+3
source

Source: https://habr.com/ru/post/1756170/


All Articles