views:

36

answers:

2

Hi,

I have a series of select boxes within a table like so:

<tr>
<td><select></select></td>
<td><select></select></td>
<td><select></select></td>
<td><select></select></td>
</tr>

With about 10 rows.

I'm trying to reset all of the select boxes in the row to a default value, but having trouble with the syntax, can anyone help? This is what I have at the moment, but it dosen't seem to be working:

$(row).children('td > select').each().val('0');

Any advice appreciated.

Thanks.

+1  A: 

If you are trying to simply select a default value, this should work (not tested):

$('select', row).each(function() {
    this.selectedIndex = 0; //or whatever the index you want
});

Using $('select', row) is a bit faster than the selector you have, so is accessing directly the objects property, instead of using the jQuery object.

jeanreis
Thanks, that was exactly what I was after!
Dan
A: 

You don't need each at all, jQuery handles applying the change to all matched elements for you:

$(row).children('td > select').val('0');

Note that that sets the value of the select box, e.g., makes the option with the matching value selected. It's not the same as setting the index of the selected option (another of the answers here shows you how to do that). Using an example with non-numeric values makes the distinction a bit clearer:

HTML:

<div id='characters'>
<select name='favorite'>
<option value='fred'>Fred Flintstone</option>
<option value='barney'>Barney Rubble</option>
<option value='wilma'>Wilma Flintstone</option>
<option value='betty' selected>Betty Rubble</option>
</select>
<select name='secondchoice'>
<option value='fred'>Fred Flintstone</option>
<option value='barney selected'>Barney Rubble</option>
<option value='wilma'>Wilma Flintstone</option>
<option value='betty'>Betty Rubble</option>
</select>

jQuery call to change both of those to 'wilma':

$('#characters select').val('wilma');

...or (perhaps more sensibly for that particular example) to having no options selected at all:

$('#characters select').val('');
T.J. Crowder