views:

44

answers:

1

Following on from my previous two questions:

http://stackoverflow.com/questions/3310387

http://stackoverflow.com/questions/3307520

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  A: 

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);
                    }
                }
        }
    });
}); 
dejavu
Cheers for the answer, I will try it on Monday (just so you know I haven't disappeared, and will green-tick when I get it working!)
Stephen
This was perfect. Thank you.
Stephen
You are welcome. :)
dejavu