Add 'selected' attribute using the option

2019-04-23 00:53发布

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

5条回答
家丑人穷心不美
2楼-- · 2019-04-23 01:30

This works:

var optionValue  = localStorage.getItem("Select1")
$("#selectbox").val(optionValue)
.find("option[value=" + optionValue +"]").attr('selected', true);
查看更多
时光不老,我们不散
3楼-- · 2019-04-23 01:30

This is all you should need:

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

I've updated a previous fiddle for an example: http://jsfiddle.net/uY7ck/1/

EDIT: In the code you posted originally, assuming you are setting localStorage with the same select box, you would be comparing "Option1" (no space) with "Option 1" (space). That comparison will never work, so the option would never be selected.

查看更多
趁早两清
4楼-- · 2019-04-23 01:31

On further review, it looks as though you wanted something more fully feature link

search = "Option 5";
$('#selectbox option:contains('+search+')').prop('selected',true);
查看更多
Root(大扎)
5楼-- · 2019-04-23 01:39

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/

查看更多
闹够了就滚
6楼-- · 2019-04-23 01:51

Try this:

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

if you are using a version of jQuery 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);
}
查看更多
登录 后发表回答