onchange event in select tag!
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?
<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..
Suggestions?
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:
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:
<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:
<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>
document.forms[0].elements['ParentSelect']
returns whole input, if you want to set it's value use
document.forms[0].elements['ParentSelect'].value = 1
精彩评论