How to set the first option on a select box using jQuery?

JavascriptJquery

Javascript Problem Overview


I have two HTML select boxes. I need to reset one select box when I make a selection in another.

<select id="name" >
    <option value="">select all</option>
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

<select id="name2" >
    <option value="">select all</option>
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

When I select an option of the first select (i.e. id="name"), I need to reset the second select to select all; similarly, when I select an option of the second select (i.e. id="name2"), I need to reset the first select to select all.

How can I do that?

Javascript Solutions


Solution 1 - Javascript

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);
});

Solution 2 - Javascript

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.

Solution 3 - Javascript

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') );
});

Solution 4 - Javascript

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());

Solution 5 - Javascript

This helps me a lot.

$(yourSelector).find('select option:eq(0)').prop('selected', true);

Solution 6 - Javascript

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);

Solution 7 - Javascript

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');
     });
 });

Solution 8 - Javascript

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('');
});

Solution 9 - Javascript

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'));
      });

Solution 10 - Javascript

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");

Solution 11 - Javascript

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>

Solution 12 - Javascript

You can try this:

$( 'select' ).each( function () {
    if ( $( this ).children().length > 0 ) {
        $( $( this ).children()[0] ).attr( 'selected', 'selected' );
        $( this ).change();
    }
} );

Solution 13 - Javascript

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.

Solution 14 - Javascript

I created a new option in the select tag that has a value of empty string ("") and used:

$("form.query").find('select#topic').val("");

Solution 15 - Javascript

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;
	}
});

Solution 16 - Javascript

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>

Solution 17 - Javascript

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);
})

Solution 18 - Javascript

$('#name').prop('selectedIndex', 0), 
$('#name').attr('selected', 'selected'), 
$('#name').find('select option:eq(0)').prop('selected', true), 
$("#name option[value=none]")

All of those options would work only if you add .change() to it to update your dropdown to show the first option.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnishView Question on Stackoverflow
Solution 1 - JavascriptJackView Answer on Stackoverflow
Solution 2 - JavascriptAndreasTView Answer on Stackoverflow
Solution 3 - JavascriptJens RolandView Answer on Stackoverflow
Solution 4 - JavascriptSatheshView Answer on Stackoverflow
Solution 5 - JavascriptAndrej GasparView Answer on Stackoverflow
Solution 6 - JavascriptIanView Answer on Stackoverflow
Solution 7 - JavascriptMuhammad UsmanView Answer on Stackoverflow
Solution 8 - JavascriptAzam AlviView Answer on Stackoverflow
Solution 9 - JavascriptNick BarrettView Answer on Stackoverflow
Solution 10 - JavascriptChamod PathiranaView Answer on Stackoverflow
Solution 11 - JavascriptmightytightywtyView Answer on Stackoverflow
Solution 12 - JavascriptAki143SView Answer on Stackoverflow
Solution 13 - JavascriptspyleView Answer on Stackoverflow
Solution 14 - JavascriptLeye OdumuyiwaView Answer on Stackoverflow
Solution 15 - JavascriptJohn MagnoliaView Answer on Stackoverflow
Solution 16 - JavascriptSjoerd LindersView Answer on Stackoverflow
Solution 17 - JavascriptAnhView Answer on Stackoverflow
Solution 18 - JavascriptValView Answer on Stackoverflow