jQuery选择值在更改时切换为默认值
我的密码在这里 还有htmljQuery选择值在更改时切换为默认值,jquery,Jquery,我的密码在这里 还有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
<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”元素的值
$("#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() + "]");
});
问题是,如果您添加
nice,您试图强制选择的值在其选项中不存在代码>选择,您的代码将工作
尝试选项:选中的
,如:
$("#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() + "]");
});
我在更新了您的小提琴。I
没有值,如何设置s
?单击按钮后选择并更改s,单击按钮时设置我。检查jsfiddlebuti
是一个字符串,s
具有可选值0,1,2,这就是它。非常感谢你在过去的5个小时里一直让我发疯这就是重点。我试图强制选择一个值。此值不在列表中,它来自不同的输入。通过使用@Lochemage建议的内容,可以将所选选项的值附加/更改为输入字段中的新值
$("#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() + "]");
});