Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 'selected' attribute using the option value

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

like image 340
jQuerybeast Avatar asked Sep 19 '11 15:09

jQuerybeast


People also ask

How add data attribute to select option?

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 .

How do you select options with value?

var variableValue = $("selector option: selected"). text(); The “option: selected” attribute is used to select specific content in the option tag.


2 Answers

This works:

var optionValue  = localStorage.getItem("Select1")
$("#selectbox").val(optionValue)
.find("option[value=" + optionValue +"]").attr('selected', true);
like image 55
jQuerybeast Avatar answered Oct 05 '22 22:10

jQuerybeast


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/

like image 26
Jack Avatar answered Oct 06 '22 00:10

Jack