使用选项值添加“selected”属性 [英] Add 'selected' attribute using the option value

查看:133
本文介绍了使用选项值添加“selected”属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带10个选项的选择框。每次选择一个选项时,都会在本地存储设置您使用idselect1选择的值。



例如:如果您选择了localstorage中的第一个选项:Key:Emailclient - Value:Option1。



现在,我试图使本地存储的值,select表单中选定的属性。



这是我试过但似乎不起作用:

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

我在做什么错?



编辑:



这是我的代码:

 < select id =selectbox> 
< option>默认< / option>
< option>选项1< / option>
< option>选项3< / option>
< option>选项3< / option>
< option>选项4< / option>
< option>选项5< / option>
< option>选项6< / option>
< / select>

谢谢

解决方案

这样做:

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


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

解决方案

This works:

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

这篇关于使用选项值添加“selected”属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆