I have list of checkboxes with certain names suffix which i wanted to loop through. those checkboxes have some custom attribute which i wanted to mainupulate.there are other checboxes which i wanted to ignore.my current code is like this
name of suffix is IsCheckedCurrently
$(document)
.off("change", "#MyDropDown")
.on("change", "#MyDropDown", function (e) {
e.preventDefault();
var teamKey = unescapeHtml($(this).val());
$('input[type=checkbox]').each(function () {
var teamKeys = $(this).attr('data-teamkeys');
if (teamKeys != undefined) {
if (teamKeys != "") {
var ischeckPreviouslyItem = $("[name='" $(this).attr('name').replace("IsCheckedCurrently", "IsCheckedPreviously") "']");
if (teamKeys.includes(teamKey)) {
if (!this.checked) {
this.checked = true;
this.enabled = true;
ischeckPreviouslyItem.prop("checked", true);
}
}
else {
if (this.checked) {
this.checked = false;
ischeckPreviouslyItem.prop("checked", false)
}
}
}
}
});
});
function unescapeHtml(safe) {
return safe.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
I have limited experteses in javascript as i am more of backend (.net C#) developer
following line i wanted to change which will include checkbox and name conditon
$('input[type=checkbox]').each(function () {
<input type="checkbox" name="FIELD_PREFIX_9.IsCheckedCurrently" id="AHREF_9" checked="checked" value="true" >
<script src="https://ajax.microsoft.com/ajax/jquery/jquery-3.6.0.js" type="text/javascript"></script>
CodePudding user response:
Change
$('input[type=checkbox]')
to
$('input[type=checkbox][name$="_ModayCheckBoxes"]')
to only match checkboxes whose name ends with that suffix.
See Attribute Ends With Selector [name$=”value”] documentation.
$("input[type=checkbox][name$=_ModayCheckBoxes").each(function() {
console.log($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Box 1 <input type="checkbox" name="Foo_ModayCheckBoxes" value="foo">
<br> Box 2 <input type="checkbox" name="Bar_ModayCheckBoxes" value="bar">
<br> Box 3 <input type="checkbox" name="Something_Else" value="xxx"><br>