将选项值设置为选中状态 [英] Set an option value as selected
本文介绍了将选项值设置为选中状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想加载一个选择框,其中用户的选择值将自动出现。
我正从服务器接收用户信息的Json数据。
数据样本是: {color:red}
我有这样的选择:
< select id =input_userclass =selectinputdisabled =true> ;
< option value =n / a>不适用< /选项>
< option value =red>红色< /选项>
< option value =green>绿色< /选项>
< option value =yellow>黄色< /选项>
< option value =blue>蓝色< /选项>
< option value =white>白色< /选项>
< / select> //这只会显示n / a作为默认
我试过这段代码让红色值作为默认值,但不工作。
var user_color = data [2] .color; //这是从json数据
document.getElementById('input_user')。selectedIndex = user_color;
任何帮助?
解决方案
正如你用jQuery标记了这个问题,你可以在上设置
直接: val()
select
var user_color ='red'; //data[2].color;$('#input_user').val(user_color);
< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< ; select id =input_userclass =selectinputdisabled =true> < option value =n / a> n / a< / option> < option value =red>红色< / option> < option value =green>绿色< / option> < option value =yellow> yellow< / option> < option value =blue>蓝色< / option> < / />选项值=白色>白色< / option>< / select>
I would like to load a select box where in the user's selected value will automatically appear.
I am receiving a Json data from the server with the user info. sample of data is:
{"color":"red"}
In my html code I have select option like this:
<select id="input_user" class="selectinput" disabled="true"> <option value="n/a"> n/a </option> <option value="red"> red </option> <option value="green"> green </option> <option value="yellow"> yellow </option> <option value="blue"> blue </option> <option value="white"> white </option> </select> //this will only show "n/a" as default
I tried this code to make the red value as default but not working.
var user_color= data[2].color; // this was from the json data document.getElementById('input_user').selectedIndex = user_color;
Any help?
解决方案As you've tagged this question with jQuery you can just set the
val()
on theselect
directly:var user_color = 'red'; //data[2].color; $('#input_user').val(user_color);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="input_user" class="selectinput" disabled="true"> <option value="n/a">n/a</option> <option value="red">red</option> <option value="green">green</option> <option value="yellow">yellow</option> <option value="blue">blue</option> <option value="white">white</option> </select>
这篇关于将选项值设置为选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆