jQuery UI autocomplete with item and id

前端 未结 11 1799
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:32

I have the following script which works with a 1 dimensional array. Is it possible to get this to work with a 2 dimensional array? Then whichever item is selected, by clic

11条回答
  •  渐次进展
    2020-11-29 00:54

    My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.

    $('#sistema_select').autocomplete({
    
        minLength: 3,
        source:  ,
        select: function (event, ui) {
             $('#sistema_select').val(ui.item.label); // display the selected text
             $('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
             return false;
         },
        change: function( event, ui ) {
            $( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
        } 
    });
    

    In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don´t get the wrong (outdated) id. For example, if my source is:

    var $local_source = [
           {value: 1,  label: "c++"}, 
           {value: 2,  label: "java"}]
    

    and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can´t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.

提交回复
热议问题