Reputation: 13
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?
Upvotes: 0
Views: 414
Reputation: 9281
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]);
});
});
Upvotes: 1
Reputation: 25527
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++;
});
});
Upvotes: 0