javascript 选择标签中的 onchange 事件!
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5572150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onchange event in select tag!
提问by Shilpa
The following code should give me a 1 in ParentSelect if I change the option in the menu, but I am getting a 0. Can anyone tell me what is the error?
如果我更改菜单中的选项,下面的代码应该在 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>
Here, I have two tables in the database. They contain some fields like ServerName, etc..
在这里,我在数据库中有两个表。它们包含一些字段,如 ServerName 等。
Suggestions?
建议?
回答by Chris Baker
You are directly assigning the value 1
to the property document.forms[0].elements['ParentSelect']
, whereas you presumably mean to change the value of the element, which would be achieved like this:
您直接将值分配给1
property document.forms[0].elements['ParentSelect']
,而您大概是想更改元素的值,这将像这样实现:
document.forms[0].elements['ParentSelect'].value = 1
document.forms[0].elements['ParentSelect'].value = 1
I agree with some of the other comments concerning the lack of valid HTML strucutre, and I would add that if you are going to reference the field via document.forms[0]
, you may as well give the field an id property so you can simply use 'document.getElementById` so your code works regardless of the other forms on the page. Anyway, using your method, here is the complete code:
我同意其他一些关于缺少有效 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>
Using an id instead:
使用 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>
回答by dev-null-dweller
document.forms[0].elements['ParentSelect']
returns whole input, if you want to set it's value use
document.forms[0].elements['ParentSelect']
返回整个输入,如果你想设置它的值使用
document.forms[0].elements['ParentSelect'].value = 1