juan
juan

Reputation: 81912

jQuery and ASP.NET names

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?

Upvotes: 6

Views: 2434

Answers (6)

Dan Appleyard
Dan Appleyard

Reputation: 7445

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.

Upvotes: 0

Jaime
Jaime

Reputation: 6814

You can do

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

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827606

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");

Upvotes: 13

Jeff Davis
Jeff Davis

Reputation: 4797

I always used this notation

$('#ctl00_Content_chkOk:checked').length; // will evaluate as true when checked

Upvotes: 1

AdamB
AdamB

Reputation: 9100

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

Upvotes: 0

Glavić
Glavić

Reputation: 43572

$('#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 ;)

Upvotes: 0

Related Questions