I have two HTML select
boxes. I need to reset one select
box when I make a selection in another.
Use jquery for binding onchange event to select but you don't need to create another $(this)
jquery object.
$('select[name=name2]').change(function(){
if (this.value) {
console.log('option value = ', this.value);
console.log('option text = ', this.options[this.selectedIndex].text);
// Reset selected
this.selectedIndex = this.defaultSelected;
}
});
Here is how I got it to work if you just want to get it back to your first option e.g. "Choose an option" "Select_id_wrap" is obviously the div around the select, but I just want to make that clear just in case it has any bearing on how this works. Mine resets to a click function but I'm sure it will work inside of an on change as well...
$("#select_id_wrap").find("select option").prop("selected", false);
You can try this:
$( 'select' ).each( function () {
if ( $( this ).children().length > 0 ) {
$( $( this ).children()[0] ).attr( 'selected', 'selected' );
$( this ).change();
}
} );
I had a problem using the defaultSelected property in the answer by @Jens Roland in jQuery v1.9.1. A more generic way (with many dependent selects) would be to put a data-default attribute in your dependent selects and then iterate through them when reseting.
<select id="name0" >
<option value="">reset</option>
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
<select id="name1" class="name" data-default="1">
<option value="">select all</option>
<option value="1" selected="true">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
<select id="name2" class="name" data-default="2">
<option value="">select all</option>
<option value="1">Text 1</option>
<option value="2" selected="true">Text 2</option>
<option value="3">Text 3</option>
</select>
And the javascript...
$('#name0').change(function(){
if($('#name0').val() == '') {
$('select.name').each(function(index){
$(this).val($(this).data('default'))
})
} else {
$('select.name').val($('#name0').val() );
}
});
See http://jsfiddle.net/8hvqN/ for a working version of the above.
This can also be used
$('#name2').change(function(){
$('#name').val('');//You can set the first value of first one if that is not empty
});
$('#name').change(function(){
$('#name2').val('');
});