Thursday, 1 October 2009

jQuery and

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

Normal Javascript:


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:


Again, just as bad as the first normal Javascript example

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

This is ok compared to the javascript version


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;


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

That is all.


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

No comments: