我的代码在http://jsfiddle.net/2BcS3/
$("#b").click(function(){
//should output: [user selection] - []
alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]");
$("#i").val('nice');
//should output: [user selection] - [nice]
alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]");
//should output: [nice] - [nice]
$("#s").val($("#i").val());
alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]");
});
和html
<select id='s'>
<option value='0'>select</option>
<option value='1'>ok</option>
<option value='2'>no</option>
</select>
<input id='i' type='hidden' />
<button type='button' id='b'>go</button>
你马上会注意到这个问题。我试图将select的值更改为动态隐藏字段中输入的内容。由于某种原因,select不会接受新值并自动切换到选择列表的第一个值!!!
答案 0 :(得分:1)
问题在于您尝试强制选择具有在其选项中不存在的值,如果您将<option value='nice'>nice!</option>
添加到选择中,您的代码将有效...
答案 1 :(得分:0)
您需要使用当前选择的选项,而不仅仅是'select'元素的值。
$("#s :selected").val();
您的脚本应该更像这样:
$("#b").click(function(){
//should output: [user selection] - []
alert("[" + $("#s :selected").val() + "] - [" + $("#i").val() + "]");
$("#i").val('nice');
//should output: [user selection] - [nice]
alert("[" + $("#s :selected").val() + "] - [" + $("#i").val() + "]");
//should output: [nice] - [nice]
$("#s :selected").val($("#i").val());
alert("[" + $("#s :selected").val() + "] - [" + $("#i").val() + "]");
});
答案 2 :(得分:0)
尝试option:selected
,例如:
$("#b").click(function(){
//should output: [user selection] - []
alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]");
$("#i").val('nice');
//should output: [user selection] - [nice]
alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]");
//should output: [nice] - [nice]
$("#s option:selected").attr('value', $("#i").val());
alert("[" + $("#s").val() + "] - [" + $("#i").val() + "]");
});
我在http://jsfiddle.net/2BcS3/3/更新了你的小提琴。