jQuery Set Default Checkbox
Set the default checkbox on startup for a checkboxlist.
HTML
<html>
<head>
<title>JS Bin</title>
</head>
<body>
<span id="cbl" class="cblAddRemove">
<input id="cb0" type="checkbox">
<label for="cb0">Add</label>
<input id="cb1" type="checkbox">
<label for="cb1">Remove</label>
<input id="cb2" type="checkbox">
<label for="cb2">Place</label>
</span>
</body>
</html>
JavaScript
// Revised
function SetCheckBoxListSelectedValue(id, value) {
// Get the desired element
var cblCtrl = $("#" + id);
if (cblCtrl !== null) {
// Loop through the desired element children that are 'labels'
var labels = cblCtrl.children("label").each(function() {
// If the desired value matches the label...
if (this.innerText == value) {
// ...locate the related checkbox and check it
$("#" + $(this).attr("for")).attr("checked", true);
}
});
}
}
// Original
function SetCheckBoxListSelectedValue_ORG(id, value) {
var cblctrl = $("#" + id);
if (cblctrl !== null) {
var options = cblctrl[0].getElementsByTagName("input");
var labels = cblctrl[0].getElementsByTagName("label");
for (i = 0; i < labels.length; i++) {
options[i].checked = false;
if (labels[i].innerText == value) {
options[i].checked = true;
}
}
}
}
SetCheckBoxListSelectedValue("cbl", "Remove");