如果我更改菜单中的选项,以下代码应该在 ParentSelect 中为我提供 1,但我得到的是 0。谁能告诉我错误是什么?
<input type="hidden" name="ParentSelect" value="0" />
<select class="style" onchange="document.forms[0].elements['ParentSelect']=1" >
<option value="NULL">NULL</option>
...
</select>
这里,我在数据库中有两个表。它们包含一些字段,例如 ServerName 等。
建议?
最佳答案
您直接将值 1
分配给属性 document.forms[0].elements['ParentSelect']
,而您大概是想更改的值元素,这将像这样实现:
document.forms[0].elements['ParentSelect'].value = 1
我同意其他一些关于缺乏有效 HTML 结构的评论,我想补充一点,如果您要通过 document.forms[0]
引用该字段,您可以我们将为该字段提供一个 id 属性,这样您就可以简单地使用“document.getElementById”,这样您的代码就可以正常工作,而不管页面上的其他表单如何。无论如何,使用你的方法,这里是完整的代码:
<form>
<input type="hidden" name="ParentSelect" value="0" />
<select class="style" onchange="document.forms[0].elements['ParentSelect'].value=1" >
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
</form>
改用 id:
<form>
<input id="parentSelect" type="hidden" name="ParentSelect" value="0" />
<select class="style" onchange="var e = document.getElementById('parentSelect'); if (e) e.value=1;" >
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
</form>
关于javascript - 选择标签中的 onchange 事件!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5572150/