Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I get the first select option in jQuery selected?

Select the <select> element using JQuery selector. This selector is more specific and selecting the first element using option:nth-child(1). This will get access to the first element (Index starts with 1).

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

How do you select the first selection option in HTML?

By the HTML 4.01 spec, browser behavior is undefined if none of the option elements has the selected attribute, and what browsers do in practice is that they make the first option pre-selected. As a workaround, you could replace the select element by a set of input type=radio elements (with the same name attribute).


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

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.


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

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