Add checkbox to auto complete -jQuery

后端 未结 1 1174
既然无缘
既然无缘 2021-01-15 18:58

I am working on this code and I have used jQuery UI for autocomplete. Now I need some help in adding check-boxes to it so that i can do multiple selections and it reflect on

相关标签:
1条回答
  • 2021-01-15 19:19

    Basically you first need to alter the jQuery autocomplete's output.

    Something like this

    $('yourElement').autocomplete({ /* autocomplete config here */ }).data( "autocomplete" )._renderItem = function( ul, item ) {
        var checked = ($.inArray(item.label, selectedItems) >= 0 ? 'checked' : '');
    
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( '<a><input type="checkbox" ' + checked + '/>' + item.label + '</a>' )
            .appendTo( ul );
    };
    

    Then you have to store the picked elements in a variable (an array)

    $('#yourElement').autocomplete({
        // Configs
        select:function(event, ui) {// Onselect event
            // Don't forget to check if the item is already in the array
            // and if it's the case to remove it
    
            selectedItems.push(ui.item.label); 
        }
    });
    

    Take not that selectItems is an array, you'll need define in your script

    You can see on this JSFiddle what this code gonna output in the autocomplete's list

    Hope it will help you a bit

    0 讨论(0)
提交回复
热议问题