How to create a Dynamic Bootstrap Multiselect

江枫思渺然 提交于 2019-12-09 14:19:42

问题


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/


回答1:


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
    });
});



回答2:


You need to add

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

to the end of your button click event to rebuild the multiselect.




回答3:


You can append your list to bootstrap ul and to your select

$('.multiselect-container').append(htm);
$('#chkveg').append(htm);

here is new Demo: http://jsfiddle.net/pL4hg76b/2/



来源:https://stackoverflow.com/questions/30300621/how-to-create-a-dynamic-bootstrap-multiselect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!