I have two HTML select
boxes. I need to reset one select
box when I make a selection in another.
Use the code below. See it working here http://jsfiddle.net/usmanhalalit/3HPz4/
$(function(){
$('#name').change(function(){
$('#name2 option[value=""]').attr('selected','selected');
});
$('#name2').change(function(){
$('#name option[value=""]').attr('selected','selected');
});
});
I created a new option in the select tag that has a value of empty string ("") and used:
$("form.query").find('select#topic').val("");
Here is the best solution im using. This will apply for over 1 slectbox
$("select").change(function(){
var thisval = $(this).val();
$("select").prop('selectedIndex',0);
$(this).val(thisval);
})
Something like this should do the trick: https://jsfiddle.net/TmJCE/898/
$('#name2').change(function(){
$('#name').prop('selectedIndex',0);
});
$('#name').change(function(){
$('#name2').prop('selectedIndex',0);
});
Here's how to handle it with a random option element defined as the default value (in this case Text 2 is the default):
<select id="name2" >
<option value="">select all</option>
<option value="1">Text 1</option>
<option value="2" selected="selected">Text 2</option>
<option value="3">Text 3</option>
</select>
<script>
$('#name2 option[selected]').prop('selected', true);
</script>
As pointed out by @PierredeLESPINAY in the comments, my original solution was incorrect - it would reset the dropdown to the topmost option, but only because the undefined
return value resolved to index 0.
Here's a correct solution, which takes the selected
property into account:
$('#name').change(function(){
$('#name2').val(function () {
return $(this).find('option').filter(function () {
return $(this).prop('defaultSelected');
}).val();
});
});
DEMO: http://jsfiddle.net/weg82/257/
Original answer - INCORRECT
In jQuery 1.6+ you need to use the .prop method to get the default selection:
// Resets the name2 dropdown to its default value
$('#name2').val( $('#name2').prop('defaultSelected') );
To make it reset dynamically when the first dropdown changes, use the .change event:
$('#name').change(function(){
$('#name2').val( $('#name2').prop('defaultSelected') );
});