Black
Black

Reputation: 20232

Selected attribute of select options is not updating automatically

I have multiple selects on my page, each has multiple options. However, If I select an option then the attribute selected of the option is not updating. Shouldn't this happen automatically?!

Example:

<select id="browsers">
  <option value="Firefox">Bing</option>
  <option value="InternetExplorer" selected="selected">Internet Explorer</option>
  <option value="Chrome">Chrome</option>
</select>

By inspecting the DOM with the developer console, you should see, that the selected attribute is not changing even after selecting another option.

However I found a workaround. To solve this issue we can use this code:

$(document).on("change","select",function() {
    $("option[value=" + this.value + "]", this)
        .attr("selected", true).siblings()
        .removeAttr("selected")
});

Example:

    $(document).on("change","select",function() {
    	$("option[value=" + this.value + "]", this)
    		.attr("selected", true).siblings()
    		.removeAttr("selected")
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="browsers">
      <option value="Firefox">Bing</option>
      <option value="InternetExplorer" selected="selected">Internet Explorer</option>
      <option value="Chrome">Chrome</option>
    </select>

This works kind of. However, If I select another option than the default option, e.g. Chrome and reload the page, then the option Chrome is still selected even after reload, BUT the selected attribute still points to Internet Explorer!

Which is the best approach to solve this? My idea is to run through all selects on $(document).ready() and select the option where the selected attribute points to.

But why does this all not happen automatically? Is it a bug or a feature?

Upvotes: 2

Views: 7512

Answers (4)

Ian Devlin
Ian Devlin

Reputation: 18870

You can check the value of the select when it changes to see what it has been changed to.

var select = document.getElementById('browsers');
select.addEventListener('change', function(e) {
  localStorage.setItem('browser', this.value);
});

var browser = localStorage.getItem('browser');
if (browser) {
  select.value = browser;
}
<select id="browsers">
  <option value="Firefox">Firefox</option>
  <option value="InternetExplorer" selected="selected">Internet Explorer</option>
  <option value="Chrome">Chrome</option>
</select>

edit

So, I missed the part about storing the value so that it persists when the page is reloaded, and depending on the OP's use case, I would suggest using localStorage to save the value when it is changed, and to read from it when the page is reloaded. I have edited the snippet to reflect this (code is simplified)

Upvotes: 1

Black
Black

Reputation: 20232

The problem before was, that after selecting an option and reloading the page, the option was remembered during page reload, even though the attribute selected pointed to another option.

I solved it by calling the function below everytime. The function finds out which is the truly selected option, even after page reload.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="downloadSelect" id="select_179">
    <option value="-">Please select</option>
    <option value="link_2748" selected="selected">Deutsch</option>									
    <option value="link_2749">Chinese</option>
</select>

<button onclick="return showSelectedOption('select_179');">Show Option Text</button>

<script>
function showSelectedOption(pSelectID)
{
    var text;
    
     $("#"+pSelectID)
    	.find("option")
      .each(function(){
    		if ($(this).prop("selected")) {
        	
        	text = $(this).text();
        }
    });
    console.log(text);
}
</script>

Upvotes: 1

LaughingMan
LaughingMan

Reputation: 650

The selected attribute defines if an element should be selected on pageload. If you post a form with a select element, the chosen option will be the one posted, regardless of the initial selected element.

What do you need the selected-attribute for in your case?

Edit: Based on your comments I made a fiddle

Fiddle 1 https://jsfiddle.net/q3fpafov/1 selects like you want

Fiddle 2 https://jsfiddle.net/bge9bsa7/2/ only files available for a chosen language are shown

I hope it's somewhere along the lines of what you're looking for. The reason for your option still being selected when you reload is browser based. But the selected-attribute does nothing for the usability of the option. Also, it won't change because you don't change the way the HTML-element itself is being rendered (at page load)

Upvotes: 2

CodeSmith
CodeSmith

Reputation: 3197

Note: selected="selected" is not necessary, simply selected attribute will work as well.

When present, select attribute specifies that an option in select should be pre-selected when the page loads.

Also, the pre-selected option will be displayed first in the drop-down list.

Those 2 should be only effects of the selected attribute. Note the keywords - when the page loads. He is either there or not when a browser loads the page.

If you wanna make it dynamic you need to use JavaScript. What do you wanna achieve with this? Having attribute selected on the correct element when reloading page or programmatically select the correct element after the page has been loaded?

If you simply wanna make element selected there is easier way trough either value:

    jQuery("#browsers[value='the value of the one you like']").attr('selected','selected');

Or by index (mind, indexes start at 0 not 1):

    document.getElementById("browsers").selectedIndex = "2";

Upvotes: 1

Related Questions