Thursday, 1 October 2009

jQuery and asp.net

There are many ways to get asp.net control values from javascript. Here are a couple of ways with pro’s/cons

Normal Javascript:

document.getElementById('ctl00_ContentPlaceHolder1_TextBox1').value

This is massivly hard coded and bad. If you change the content place holder, or refactor this into a user control this will no longer work. But this is quick.

document.getElementById('<%=TextBox1.ClientID %>').value

This is less hard coded which is good, but the code can be a bit tricky to read.

With jQuery:

$('#ctl00_ContentPlaceHolder1_TextBox1')[0].value

Again, just as bad as the first normal Javascript example

$('#<%=TextBox1.ClientID %>')[0].value

This is ok compared to the javascript version

$('input[id$=TextBox1]')[0].value

This is probably my favorite method. This tells jquery to search for an input where the id ends with TextBox1 – be careful you have no other TextBox1 ids on the page!

Note the array indexer. This is because jquery returns an array of all the items it finds. This means if you have a grid with 12 rows you can access all of the textbox1’s using

$('input[id$=TextBox1]')[0].value -> $('input[id$=TextBox1]')[12].value

Now you are probably asking why would you just use the first javascript example. This is reasonable for a text box but say you are using a drop down list – which looks better:

var CustomerInputbox = document.getElementById('<%=ddlCustomer.ClientID %>');

var CustomerID = CustomerInputbox.options[CustomerInputbox.selectedIndex].value;

or

var CustomerID = $('select[id$=ddlCustomer] option:selected')[0].value

That is all.

Ross

P.S. Learn to love jQuery, resistance is futile.

No comments: