Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Dynamic Bootstrap Multiselect

I am trying to use Bootstrap multiselect , I used the following code

html

<input type="text" id="addRow"/>
<input type="button" id="btn" value="Add"/>
<form id="form1">
   <div style="padding:20px">
     <select id="chkveg" multiple="multiple">
     </select>
   </div>
</form>

and script

$(function () {
    $('#btn').click(function () {
        var val = $("#addRow").val();
        var htm = '';
        htm += '<option>' + val + '</option>';
        $('#chkveg').append(htm);
    });
    $('#chkveg').multiselect({
        includeSelectAllOption: true
    });
});

i am try to add each option dynamically to the bootstrap multiselect but its not working properly

Demo page here : http://jsfiddle.net/pL4hg76b/1/

But its working statically : http://jsfiddle.net/KyleMit/7yq7fvsq/

like image 413
Chithra Mohan Avatar asked May 18 '15 10:05

Chithra Mohan


People also ask

How do you use multiselect?

Definition and Usage For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

How set multiple selected values in Dropdownlist jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.


1 Answers

You need to use .multiselect('rebuild') method of multiselect after you use .append()

$('#chkveg').multiselect('rebuild');

Updated Fiddle


Full code

$(function () {
    $('#btn').click(function () {
        var val = $("#addRow").val();
        var htm = '';
        htm += '<option>' + val + '</option>';
        $('#chkveg').append(htm);
        $('#chkveg').multiselect('rebuild');
    });
    $('#chkveg').multiselect({
        includeSelectAllOption: true
    });
});
like image 92
Shaunak D Avatar answered Sep 21 '22 13:09

Shaunak D