I want to assign unique incremental values to dynamically generated checkboxes, starting from 0 onwards and incrementing by 1, (i.e, the checkboxes values should be 0,1,2,3 and so on). I have the following code snippet which is kind of an abstract of the bigger picture :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title></title>
<script src="knockout-3.3.0.js"></script>
</head>
<body>
<table>
<tbody data-bind="foreach:arr">
<tr>
<td><input type="checkbox" data-bind="checked : $root.ch, attr : {value : $root.ci}"></td>
</tr>
</tbody>
</table>
<button data-bind="click:add">Click</button>
<button data-bind="click:func">Checked</button>
<script type="text/javascript">
var viewModel = {
ci : ko.observable("0"),
ch : ko.observableArray([]) ,
arr : ko.observableArray([]),
add : function(){
alert(viewModel.ci());
viewModel.arr.push("something");
var temp = Number(viewModel.ci());
temp++;
viewModel.ci(ko.toJSON(temp));
},
func : function(){
for(var i = 0; i < viewModel.ch().length; i++)
{
alert(viewModel.ch()[i]);
}
}
};
ko.applyBindings(viewModel);
</script>
</body>
</html>
Initially, the UI will contain a 'Click' button and a 'Checked' button. Once the user clicks on 'Click', a new checbox is generated and value is assigned to it based on the above logic. When the user clicks 'Checked', the values of all the checkboxes are alerted one by one. Now, here's the catch : on clicking checked, it displays the values of the selected checkboxes just fine, but when you select 'Inspect element' from the browser on the checboxes, all the checkboxes get the same value which is equal to the number of checkboxes created. How to resolve this issue so that the checkboxes will have incremental values?
Aucun commentaire:
Enregistrer un commentaire