I have two HTML select
boxes. I need to reset one select
box when I make a selection in another.
Use this if you want to reset the select to the option which has the "selected" attribute. Works similar to the form.reset() inbuilt javascript function to the select.
$("#name").val($("#name option[selected]").val());
This helps me a lot.
$(yourSelector).find('select option:eq(0)').prop('selected', true);
If you just want to reset the select element to it's first position, the simplest way may be:
$('#name2').val('');
To reset all select elements in the document:
$('select').val('')
EDIT: To clarify as per a comment below, this resets the select element to its first blank entry and only if a blank entry exists in the list.
Use this code to reset all selection fields to the default option, where the attribute selected is defined.
<select id="name1" >
<option value="1">Text 1</option>
<option value="2" selected="selected" >Default Text 2</option>
<option value="3">Text 3</option>
</select>
<select id="name2" >
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3" selected="selected" >Default Text 3</option>
</select>
<script>
$('select').each( function() {
$(this).val( $(this).find("option[selected]").val() );
});
</script>
Setting option 1 in the select element can be done by this segment. To visually show it, you have tp add .trigger('change') at the end.
$('#name').removeAttr('selected').find('option:first').attr('selected', 'selected').trigger("change");
This is the most flexible/reusable way to reset all select boxes in your form.
var $form = $('form') // Replace with your form selector
$('select', $form).each(function() {
$(this).val($(this).prop('defaultSelected'));
});