Reputation: 1227
I have an post action, and when it success, i call a method and pass a the json result. Then i loop through each json object, in that loop i want to get a checkbox with objects id as a value attribute, here is how i did:
$.each(roles, function (index, role) {
var checkboxes = $('input[value="role.RoleId"][type="checkbox"]').attr("checked",true);
});
As you can see, i have a list of checkboxes and i want to select them when their value attribute is equal to "role.RoleId". But i couldn't manage to do it, how can i do it?
Edit: Well how can i select the wrapper element of that checkbox. it's in . so i need also select element?
Thanks
Upvotes: 0
Views: 160
Reputation: 268354
You can use the :checkbox
selector to shorten your code up just a bit:
$(":checkbox[value=" + role.RoleId + "]").prop("checked", true);
You want to use concatenation here so that role.RoleId
isn't interpreted literally, as plain text, but instead we want to use the value of role.RoleId
.
Upvotes: 0
Reputation: 79830
You should use .prop
instead of .attr
.
.prop("checked",true);
Also you need to append the role.RoleId.. see below,
$.each(roles, function (index, role) {
var checkboxes = $('input:checkbox[value="' + role.RoleId + '"]').prop("checked",true);
});
Upvotes: 1
Reputation: 160853
var checkboxes = $('input[value="'+role.RoleId+'"][type="checkbox"]').prop("checked",true);
But set ids to the checkboxes will make problem more simple.
Upvotes: 0
Reputation: 13461
You have to use the value or role.RoleId like this
var checkboxes = $('input[value="'+role.RoleId+'"][type="checkbox"]').attr("checked",true);
as role is a object from $.each loop.
Upvotes: 1