Anirban
Anirban

Reputation: 589

How to check Checkbox with Jquery

I have the following piece of code :

for(var i = 0, len = data.UserDetail.RoleNames.length; i < len; ++i) {
    var rolevalue = data.UserDetail.RoleNames[i];
    //alert(rolevalue)

    $('input[value = rolevalue]').attr('checked', true); // I am getting a exception in this line !! :(
}

I am not able to check the values which are already present in the checkbox. The checkbox is having the following value

<input type="checkbox" name="role" value="Admin1" />Admin1<br />
<input type="checkbox" name="role" value="Admin2" />Admin2<br />
<input type="checkbox" name="role" value="Admin3" />Admin3<br />

<input type="checkbox" name="role" value="Admin4" />Admin4<br />

What will be syntax? I have also tried using the prop() function as well but it does not work.

Upvotes: 0

Views: 296

Answers (2)

Murali Krishna
Murali Krishna

Reputation: 141

This will work too:

$('input[value='" + rolevalue + "']').is(':checked');

Upvotes: 0

SpoonNZ
SpoonNZ

Reputation: 3829

It seems a bit of an odd way to do things, but I'm guessing what you want is:

$('input[value=' + rolevalue + ']').attr('checked', true)

I'm not 100% sure that the selector works this way, but if it does, that code will be better than yours!

Upvotes: 3

Related Questions