简体   繁体   中英

how to dynamically add labels to my checklist in jquery

I want to populate my checklist from an array dynamically. How should I populate the values and labels for this checklist using jquery/javascript?

<div class="container" id="check">
    <input type="checkbox" value= array[0]/> <label></label>
    <input type="checkbox" value= array[1]/> <label></label>
    <input type="checkbox" value= array[2]/> <label></label>
</div>

How to populate the label tag with the elements of the array?

Where does the array come from? If you have the array available already in your JS, then you can try something like this

$(document).ready(function(){
    var arr = ["val1", "val2", "val3"];
    $('#check label').each(function(index){
        if(index < arr.length)
            $(this).text(arr[index]);
    });    
});

you can use this example,

       $(document).ready(function () {
        var array = [1, 2, 3];
        var i = 0;
        $("input[type=checkbox]").each(function (current) {
            alert($(this).val(array[i]));
            i++;

        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM