14

Below is code for select option and generate using php from database and i try to add selected="selected" to value="4" using jQuery or any javascript:

<select id="countryselect" name="country">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<option value="4">Malaysia</option>
<option value="5">Maldives</option>
</select>

i try to refer this post but still can't .. below is my current script :

<script>
localStorage.setItem("Select1", "Malaysia");
    $('#countryselect').find('option').each(function(i,e){
        if($(e).val() == localStorage.getItem("Select1")){
            $('#countryselect').prop('selectedIndex',i);
        }
    });
</script>

thanks.

7 Answers 7

23

The selected attribute is a boolean attribute, its presence sets the value of the related DOM property to true. If the attribute is absent, the value of the selected property is false.

If an option has the selected attribute, then when the page is first loaded, or the form the control is in is reset, that option will be the selected option.

If the option's selected property is set to true, then that option will be selected. However, if the form is reset, the default selected option will be selected (i.e. the one with the selected attribute, or the first option, or none).

To set the selected attribute (i.e. make the option the default selected option):

var select = document.getElementById('countryselect');
var option;

for (var i=0; i<select.options.length; i++) {
  option = select.options[i];

  if (option.value == '4') {
  // or
  // if (option.text == 'Malaysia') {
     option.setAttribute('selected', true);

     // For a single select, the job's done
     return; 
  } 
}

Note that this may not make the option the currently selected option, it will just add the selected attribute. To make sure it's selected (if that is what is required), the also set the selected property to true (see below).

Note that the second argument to setAttribute is supposed to be a string that is used to set the attribute's value. However, the selected attribute doesn't have a "setable" value, so the second argument is ignored (e.g. even false will still set the attribute and make the option the default selected option). That causes some confusion. :-)

To set the selected property (i.e. just make the option the current selected option):

var select = document.getElementById('countryselect');
var option;

for (var i=0; i<select.options.length; i++) {
  option = select.options[i];

  if (option.value == '4') {
  // or
  // if (option.text == 'Malaysia') {
     option.selected = true;
     return;
  } 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this super-clear explanation. Much appreciated and it worked like a charm.
16

This should work simple, $("#countryselect").val('4')​

It will automatically set selected=selected

Demo: http://jsfiddle.net/muthkum/zYRkC/

Comments

8

localStorage.getItem("Select1") will return Malaysia and $(e).val() will return 1,2...5 in each loop. So your condition will never be true. Instead use

<script>
localStorage.setItem("Select1", "4");
    $('#countryselect').find('option').each(function(i,e){
        if($(e).val() == localStorage.getItem("Select1")){
            $('#countryselect').prop('selectedIndex',i);
        }
    });
</script>

Comments

7

As of jQuery 1.6 "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method."

$("#countryselect option[value=4]").prop("selected", "selected")

Comments

1

Just try

$("#countryselect").val('4')
    //OR

$("#countryselect option").val('4')​.attr("selected", true)​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Check this FIDDLE

1 Comment

Do you mean $("#countryselect option[value=4]").attr("selected", true)?
0

const formSelect = document.querySelector("#form-select");

formSelect.selectedIndex = 3; // !
<select id="form-select">
  // ...
</select>

Link

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
-1
$('#countryselect > option[value *= "4"] ').attr('selected',true);

this will work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.