Wednesday, June 18, 2008

I was just using jQuery in an application I'm building to clone a table row which includes a couple of select elements which are preselected when the page loads. Now when I clone the row I want a clean sheet so both selects need to be reset and the input needs to be cleared too. The input is easy, you simple reference the input and set val(""). In my example I store the cloned row in a variable called newTR and then find the input that I want to clear like so:

$(newTR).find('.hours').val("");

However I was trying to reset the select elements like this:

$(newTR).find('.sel_projects').selectedIndex = -1;

This wasn't showing an errors in Firebug, it simply wasn't working. After a bit of research I found the answer. Due to jQuery's chaining mechanism you need to use either the get() method or reference the jQuery object by it's array shortcut to get to the actual DOM element. Like this:

$(newTR).find('.sel_projects').get(0).selectedIndex = -1;

OR

$(newTR).find('.sel_projects')[0].selectedIndex = -1;

Easy when you know how!

Labels:

Jon 11:41 AM Permalink