I have a select box with 10 options. Each time you select an option it sets in the localstorage the value you selected with id "select1".
For example: If you select the first option you get in the localstorage: Key: Emailclient - Value: Option1.
Now, Iom trying to make the value of the localstorage, the selected attribute in the select form.
This is what I tried but doesn't seem to work:
if (localStorage.getItem("Select1") == "Option1"){
$('#selectbox').val("Option1").attr("selected");
}
What I'm 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
HTML <option> data-* AttributeA data-* attribute on an <option> tag attaches additional data to the option item. To create a custom attribute, replace * with a lowercase string, such as data-id , data-status , or data-location .
var variableValue = $("selector option: selected"). text(); The “option: selected” attribute is used to select specific content in the option tag.
This works:
var optionValue = localStorage.getItem("Select1")
$("#selectbox").val(optionValue)
.find("option[value=" + optionValue +"]").attr('selected', true);
I think you might be looking for something like this. http://jsfiddle.net/tnPU8/3/
It loops through the options of the select box and compares their values with the values of b
. If they are equal the index of the select box is changed so that the option that contains the value of b
is 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With