Selected attribute of select options is not updating automatically - javascript

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?

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)

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

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>

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)

Related

JQuery Mobile custom dropdown issue

I'm facing an issue in selecting the dropdown first value after selecting it for the first time. When the dropdown options slidedown to select, the first value would be selected by default,bcoz of which I'm not able to select the first value. I'm using JQuery mobile framework and I'm writing custom JS to change the dropdown. I need to handle this dropdown only using custom JS and cannot make the dropdown work with this custom logic due to some other issue with my project.
Here first value im referring as 'US' from dropdown
The solution for this issue would be really appreciated. Thanks in advance.
HTML:
<select id="drpDwn">
<option value="" disabled="disabled">select</option>
<option value="US">US</option>
<option value="AU">AU</option>
<option value="NZ">NZ</option>
</select>
JS:
$(document).on('change', '#drpDwn', function () {
var index = $(this)[0].selectedIndex;
$(this).attr('selectedIndex', index);
$(this).find('option').removeAttr('selected');
$(this).find('option').eq(index).attr('selected', 'selected');
$(this).siblings('span').html($(this).find('option').eq(index).text());
});
http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js
http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css
Check out this JSFiddle
The difference maker was modifying:
$(this).find('option').removeAttr('selected');
Into:
$(this).find('option:not(:selected)').removeAttr('selected');
When 'change' was triggered, the selected attribute is added to the new option, so you were stripping it away from everything even the new selection. That's why the option never changed.
Using :not(:selected) came in handy then since it will only strip away the attribute from things that weren't the current selected option.

Angular blank option selected

I'm banging my head against the wall on this one.
I have an array of objects that will be used to populate a select drop down:
CardCount = [{"ClientId": "0010", "Description": "0010 (206 Members)"}, {"ClientId": "0051", "Description": "0051 (1 Member)"}, ........]
When I attempt to use ng-options, the value of the option is set to the index, not to the ClientId as desired. To get the value in each option to be the ClientId, I have to use a ng-repeat in the options. Here is my html:
<select ng-model="CurrentClient">
<option ng-repeat="item in CardCount" value="{{item.ClientId}}">{{item.Description}}</option>
</select>
Initially, all is well, the select and options are generated correctly, and the first option is correct. Now, when a certain button is clicked somewhere else on the page, it becomes necessary to recreate this select and options with a smaller array of similar objects. However, doing so creates a blank option with a value of "? string:0010 ?". This is the option that is selected. Again, I cannot use ng-options to correct this problem because doing so doesn't set the value attribute in the option tags correctly. So, I added this to the option tag:
<option ng-repeat="item in CardCount" value="{{item.ClientId}}" ng-selected="CurrentClient == item.ClientId">{{item.Description}}</option>
Now, that does mark the correct option as selected. However, the drop down still shows the blank option. Here's the rendered html:
<select ng-model="CurrentClient">
<option value="? string:0010 ?"></option>
<option value="0010" selected="selected">0010 (206 Members)</option>
</select>
As you can see, it sets the correct option to selected. However, it sets it to selected="selected", and not just selected. When I inspect element and change selected="selected" to selected (remove the equals and everything after it), the drop down then correctly displays the correctly selected option.
Again, initially the select and options work great. The problem seems to happen only after the array that the select is created with is changed. How can I get this select and options working correctly after I change the array, and not show that first blank option?
Thanks!
Changed you option element to set value by default.
<option ng-repeat="item in CardCount track by item.ClientId"
value="{{item.ClientId}}">{{item.Description}}</option>
Hope this could help you. Thanks.
ng-options is definitely the way to go:
<select ng-model="selected.ClientId" ng-options="it.ClientId as it.Description for it in clientList">
<option value="">-</option>
</select>

How to select the <select> tag including checked and unchecked options using queryselectorAll()?

//initial code
var selectInputs = document.querySelectorAll('option:checked');
var selectArray=[];
for(var i=0;i<selectInputs.length;i++)
{
selectArray[i]=selectInputs[i].value;//am doing this since I found out (from stackoverflow) that selectInputs contains a NodeList and in order to use it, it must be converted or saved as an array
}
//later stage manipulation code
var input_select= document.querySelectorAll('option:checked');
for(var i=0;i<input_select.length;i++)
{
input_select[i].value=selectArray[i];//I am trying to change the value of the <select> option
}
PURPOSE: User selects option in a form and data is saved in local storage.
I want to reflect the same when the form reloads. I am not working for a specific form so using Jquery seems futile(as it works with class or id and I don't know the id or class of any tag of the generic form)
PROBLEM:
The problem is that I wanna select the entire options set of tag and not just the ones that have been checked/selected.The code above sets the value of the default selected option to the one stored in local storage but doesn't reflect the change in the form. It always displays the default value though giving
alert(input_select[i].value);
reflects the internal change perfectly!
Guess I gotta answer my own question :-D
If you could see, there's just one silly change in the
//later stage manipulation code
ABOVE.
ANSWER:
var input_select= document.querySelectorAll('select');
for(var i=0;i<input_select.length;i++)
{
input_select[i].value=selectArray[i];//I am trying to change the value of the <select> option
}
Instead of
var input_select= document.querySelectorAll('option:checked');
It must be
var input_select= document.querySelectorAll('select');
REASON: I have been trying to assign the stored value into the option itself (the option tag) rather than the select tag as a whole.
WARNING: In the code
input_select[i].value=selectArray[i];
It could also be
input_select[i].value="Friday";
provided that you already have an option like that, else it would show a blank.
<select name="days" id=days">
<option value="0"> Friday </option>
<option value="1"> Monday </option>
</select>
works
<select name="days" id=days">
<option value="0"> Saturday </option>
<option value="1"> Monday </option>
</select>
doesn't work. Shows a blank.

Click already selected option in select box

This seems like it should be easy, but the limitations of the <select> object are rather irritating. I have a select box with four options, and when you navigate to a page, the option is set to the page you are on. I want to make it so that the user can refresh the page by selecting the same option - that is, selecting the option that's already selected.
Unfortunately, the onclick event doesn't work across browsers. Most people recommend using onchange, but that doesn't work in the case I'm talking about. The approach I've been taking is to add an extra item at the top that holds what's currently selected and does nothing when clicked on, and then switch to that option after firing the onchange event, so that when the user re-selects the option they're actually changing. That's awkward though, because in the drop-down there are two of the same item, and I shouldn't have to do it.
What is a good cross-browser way to solve this problem? Something not terribly complicated and something in regular JavaScript would be preferable.
This might help:
function onFocus(element){
element.setAttribute('old-value',element.value);
element.value='';
console.log('reset');
}
function onBlur(element){
if(element.value=='')
element.value = element.getAttribute('old-value');
element.removeAttribute('old-value');
}
function onChange(element){
console.log('New Value : '+ element.value);
}
<select id="mySelect" onfocus="onFocus(this)" onchange="onChange(this)" onblur="onBlur(this);">
<option value="" style="display:none;"></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
Here you go with the solution
$("select[id=mySelect] option").click(function(){
alert("HI");
});
This will alert -HI- everytime a click is made on an option. The change has also been made in the select box and event is also been performed.

Linking combo box (JQuery preferrably)

I am wondering if anyone has any experience using a JQuery plugin that converts a html
<select>
<option> Blah </option>
</select>
combo box into something (probably a div) where selecting an item acts the same as clicking a link.
I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.
Your advice, experience and recommendations are appreciated.
The simple solution is to use
$("#mySelect").change(function() {
document.location = this.value;
});
This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option.
I'm not sure where you want to link to when you click the Div, but given something like this perhaps would work:
<select id="mySelect">
<option value="1">Option 1</option>
<option value="2">Option 2</options>
</select>
<div id="myDiv"/>
and the following JQuery creates a list of <div> elements, a goes to a URL based on the value of the option:
$("#mySelect option").each(function() {
$("<div>" + $(this).text() + "</div>").appendTo($("#myDiv")).bind("click", $(this).val(), function(event) {
location.href = "goto.php?id=" + event.data;
});
});
$("#mySelect").remove();
Does this do what you want?
If you're going to have a lot of select boxes that you want to allow to use as redirects, without having to define them independently, try something similar to:
$("[id*='COMMON_NAME']").change(function() {
document.location = this.value;
});
And have your select boxes be named accordingly:
<select id="COMMON_NAME_001">...</select>
<select id="COMMON_NAME_002">...</select>
This creates a onchange event for all IDs containing "COMMON_NAME" to do a redirect of the <option> value.
This bit of javascript in the 'select':
onchange="if(this.options[this.selectedIndex].value!=''){this.form.submit()}"
It's not ideal (because form submissions in ASP.NET MVC which I'm using don't appear to use the routing engine for URLs) but it does its job.

Categories

Resources