views:

218

answers:

6

What is the correct way to get a control that was rendered by ASP.NET with jQuery?

Example: I have a checkbox that was generated like this:

<input id="ctl00_Content_chkOk" type="checkbox" name="ctl00$Content$chkOk" />

If I want to select it to get if it's checked, I tried this:

$('form input[name=chkOk]').attr("checked")

and

$('chkOk').attr("checked")

But it didn't work, I had to do it like this

$('form input[name=ctl00$Content$chkOk]').attr("checked")

And I guess this would've worked too:

$('ctl00$Content$chkOk').attr("checked")

Is this the correct way to do it? Is there another selector I can use?

A: 
$('#ctl00_Content_chkOk').attr('checked');
$('form #ctl00_Content_chkOk').attr('checked');
$('form input#ctl00_Content_chkOk').attr('checked');
$('form input#ctl00_Content_chkOk[type="checkbox"]').attr('checked');

Pick one ;)

glavić
A: 

Hi Juan,

Yeah, JQuery only cares about what is rendered on the page, whether through the ASP.NET engine or through simple HTML, so you'll have to access it via the id or name. The two bottom versions you used would work as well as $('#ct100_Content_chk0k').attr("checked").

Adam

AdamB
+1  A: 

I always used this notation

$('#ctl00_Content_chkOk:checked').length; // will evaluate as true when checked
Jeff Davis
+6  A: 

You can use the server side control ClientID property:

var isChecked = $('#<%=YourCheckBox.ClientID%>').attr("checked");

or you could use the "ends with" selector: attribute$=value

var isChecked =  $('form input[name$=chkOk]').attr("checked");
CMS
+1  A: 

You can do

$("input[id*=_chkOk]").attr('checked');

Jaime
A: 

I tend to go back and forth between two ways. I either use the control's clientID property as mentioned by CMS, or I generate the javascript code in my code behind and use the page's ClientScriptManager to write it to the browser.

Dan Appleyard