Add checkbox to auto complete -jQuery

6.7k views Asked by At

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 my field with comma separation. I found a plugin exactly what I want to create but I don't want to use any plugin for [my work] http://www.igniteui.com/combo/selection-and-checkboxes

<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
<link rel="stylesheet" href="js/jquery-ui.css">
<body>
    <input id="condition" type="text" placeholder="condition">
</body>
<script>
    var availableTags = [
               "ActionScript",
               "AppleScript",
               "Asp",
               "BASIC",
               "C",
               "C++",
               "Clojure",
               "COBOL",
               "ColdFusion",
               "Erlang",
               "Fortran",
               "Groovy",
               "Haskell",
               "Java",
               "JavaScript",
               "Lisp",
               "Perl",
               "PHP",
               "Python",
               "Ruby",
               "Scala",
               "Scheme"
    ];

    $(document).ready(function () {
        $('#condition').autocomplete({
            source: availableTags,
            minLength: 0
        }).focus(function () {
            try {
                $(this).autocomplete("search");
            }
            catch (e) {

            }
        });
    });
</script>
1

There are 1 answers

0
DFayet On

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