Reputation: 36205
I am currently working on a javascript and php project. I have a checkbox array that have the same id chkCategory
and the name chkCategory[]
. I then have PHP return some json that contains the various categories and I want to set each checkbox checked attribute for each category that was in the json. The only thing that identifies each checkbox is the value. I.e. the json may have a value MyCategory
so the checkbox that has the value MyCategory
should be set.
I know you can use $("#myCheckBoxId").attr("checked", true)
for an individual checkbox but not sure how to do this for a specific checkbox with a certain value.
Thanks for any help you can provide.
Upvotes: 2
Views: 173
Reputation:
In plain javascript it would look like this:
document.querySelector('input[value=checkboxValue]').checked = true;
where checkboxValue
is the value of your checkbox
Upvotes: 0
Reputation: 490153
If you know the index, you could do...
$("input[name='MyCategory']").eq(n).prop("checked", true);
If you don't have jQuery...
document.getElementsByName("MyCategory")[n].checked = true;
Upvotes: 1
Reputation: 102743
You can use standard CSS attribute selectors in JQuery. For example:
$("input[value=MyCategory]")
will select the input tag with attribute value=MyCategory
. If there are different types of input
s with that value, you could also select on type=checkbox
:
$("input[type=checkbox][value=MyCategory]")
Upvotes: 2