Add attribute 'selected' using option value

I have a select box with 10 parameters. Each time you select an option, it sets localstorage to the value you selected with the identifier "select1".

For example: if you select the first option that you get in localstorage: Key: Emailclient - Value: Option1.

Now Iom is trying to make the value of localstorage the selected attribute on the selection form.

This is what I tried, but does not seem to work:

if (localStorage.getItem("Select1") == "Option1"){ $('#selectbox').val("Option1").attr("selected"); } 

What am I doing wrong?

EDIT:

This is my code:

 <select id="selectbox" > <option>Default</option> <option>Option 1</option> <option>Option 3</option> <option>Option 3</option> <option>Option 4</option> <option>Option 5</option> <option>Option 6</option> </select> 

thanks

+7
source share
5 answers

It works:

 var optionValue = localStorage.getItem("Select1") $("#selectbox").val(optionValue) .find("option[value=" + optionValue +"]").attr('selected', true); 
+18
source

I think you can look for something like this. http://jsfiddle.net/tnPU8/3/

It iterates over the options of the selection field and compares their values ​​with the values ​​of b . If they are equal, the index of the selection field changes so that an option containing the value b displayed.

 var b; //set equal to what you want to compare $('#selectbox').find('option').each(function(i,e){ console.log($(e).val()); if($(e).val() == b){ $('#selectbox').prop('selectedIndex',i); } }); 

Edit: using localStorage http://jsfiddle.net/tnPU8/7/

+1
source

In further reviews, it seems to you that you need something more complete link

 search = "Option 5"; $('#selectbox option:contains('+search+')').prop('selected',true); 
0
source

Try the following:

 if (localStorage.getItem("Select1") == "Option1"){ $('#selectbox option:contains(Option1)').prop('selected',true); // jquery 1.6+ } 

if you are using jQuery version older than 1.6, replace .prop with .attr

Edit: more dynamic version

 if (localStorage.getItem("Select1")) { $('#selectbox option:contains(' + localStorage.getItem("Select1") + ')').prop('selected',true); } 
0
source

This is all you need:

 $("#selectbox").val(localStorage.getItem("selectbox")); 

I updated the previous fiddle for an example: http://jsfiddle.net/uY7ck/1/

EDIT: In the code you originally posted, assuming that you are installing localStorage with the same selection field, you are comparing β€œOption1” (without a space) with β€œOption 1” (a space). This comparison will never work, so the option will never be selected.

0
source

All Articles