user2906420
user2906420

Reputation: 1269

jQuery find checkbox and check/uncheck it

My checkboxes created in loop:

@foreach (L1 item in Model)
{
    <li><label class="checkbox"><input type="checkbox" id="@(item.Name)" 
         class="clink" value="@(item.Name)"/>@item.ForeName</label></li>
}

And then I am using jQuery to check it:

 $('#cworks').prop('checked', true);

The above is not working. here is the generated html using firebug

<label class="checkbox"><input id="cworks" class="clink" value="cworks" type="checkbox">cworks</label>

Upvotes: 0

Views: 1468

Answers (7)

hugodutra
hugodutra

Reputation: 31

Use id instead of class

$('#Careworks_Map').prop('checked', true);

Upvotes: 0

Merlin
Merlin

Reputation: 4927

In your example you set a class class="checkbox" then in the jquery call you use an id #checkbox input so to make it work you should do:

$('.checkbox input[id="somestring"]').prop('checked', true);

Then if your item.Name is set with a prefix like var item.Name = my_prefix_somestring you can use a wildcard.

 $('.checkbox input[id=*"my_prefix"]').prop('checked', true);

If item.Name are unique (which I presume) then just do :

$('#Careworks_Map').prop('checked', true);

EDIT

based on your update you should do that :

$('#cworks').prop('checked', true);

http://jsfiddle.net/daguru/7FUBn/2/

Upvotes: 1

MonkeyZeus
MonkeyZeus

Reputation: 20747

It's not working because the <label> is declaring a class="checkbox" so you need to search for class with a period . and then target the inner checkbox

$('#checkbox input[id="Careworks_Map"]').prop('checked', true); // wrong

$('.checkbox input[id="Careworks_Map"]').prop('checked', true); // right

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108520

ID’s should be unique. So it’s enough (and most efficient) to use that ID as a selector:

$('#Careworks_Map').prop('checked', true);

Upvotes: 1

John S
John S

Reputation: 21492

If the checkbox has an "id", then that is all you need to select it.

$('#Careworks_Map').prop('checked', true);

Upvotes: 1

xspydr
xspydr

Reputation: 3060

$(":checkbox input[id='Careworks_Map']").attr("checked", true);

Upvotes: 0

gabitzish
gabitzish

Reputation: 9691

You are using an id selector while you have to use a class selector :

$('.checkbox input[id="Careworks_Map"]').prop('checked', true);

You can also select directly the id of the checkbox you want to modify:

$('#Careworks_Map').prop('checked', true);

Upvotes: 0

Related Questions