I have an array of checkboxes. I need to check the boxes based on the text value for the checkbox. For examples if I have three checkboxes with the text "Checkbox 01.", "Checkbox 02." and "Checkbox 03." and I have a checkbox called "Select All". I want to iterate through the array of checkboxes and only check items that contain the word "02." or "03."
I’m not proficient in JQuery, I inherited this, but I took a stab at the code and here is what I tried:
$(".rightColumn .SelectAllGroups").on("click", function () {
if (this.checked) {
$(".GroupSelection input:checkbox").each(function (i) {
//alert("Index of item" + i);
if (this(i).val.contains("01.") || this(i).val.contains("02.") || this(i).val.contains("03.") ||
this(i).val.contains("04.") || this(i).val.contains("05.") || this(i).val.contains("06.") || this(i).val.contains("07 .") ||
this(i).val.contains("08.") || this(i).val.contains("09.") || this(i).val.contains("10.") || this(i).val.contains("11.")) {
this(i).checked = i;
}
});
} else {
$(".GroupSelection input:checkbox").each(function () {
this.checked = false;
});
}
});
Just an FYI, the value "07 ." does have a space whereas the others don’t. When I run this I get the error "This is not a function". The textboxes are created via code. Here is the result of one textbox
<input name="ctl00$ctl00$ctl00$mainBody$mainContent$main$newEpisodeForm$NewSnapshot$GroupSelection$groupTypeList$ctl01$groupList$ctl00$groupCheck" type="checkbox" id="mainBody_mainContent_main_newEpisodeForm_NewSnapshot_GroupSelection_groupTypeList_groupList_1_groupCheck_0" isoptionalgroup="true" value="ae37b870-e525-4cce-9315-1e8e4e253483">
<span id="mainBody_mainContent_main_newEpisodeForm_NewSnapshot_GroupSelection_groupTypeList_groupList_1_groupLabel_0">01. First Test</span>
Thanks.
2
Answers
Since I had an array of values for each of the checkboxes, and they were unique, I put the values in an array and then set the checkbox checked property based on the value from the array. Here is the code:
Since the values were unique because they are GUID's, then this worked to pick up the checkboxes I need.
You rather use indexOf() instead of using contain();
Get element $(this) in a var to be sure to use the right element.
You can also get elements from the clicked element by using prevAll() (or closest(), nextAll() depending on your project). Like this again, you sure to use the right element to work with.
I commented my code below :