select onChange not working inside a form

半世苍凉 提交于 2019-12-12 11:01:06

问题


I have a question about form submit & onchange events not working together. When I change the value on the dropdown list the event viewroom() is not firing. Could anyone help me with this? The code is as follows

<script type="text/javascript">
function viewroom()
{
    alert(123);
}
</script>

<form id="myform" name="myform" action="joinroom.php" method="post">
<select name="viewroom" id="viewroom" onChange="viewroom()">
    <option value="1">Room1 </option>
    <option value="2">Room2 </option>
</select>
<input type="submit" onclick="this.form.submit()" value="Join room"><br>
</form>

回答1:


Your function name conflicts with name and id of the select, just give another name to the function.




回答2:


You can't name a function the same as an element on your page. I suggest changing the function name to something like viewroomSelected as shown here in this jsFiddle.

Relevant changes:

function viewroomSelected()
{
  alert(123);
}

<select name="viewroom" id="viewroom" onChange="viewroomSelected()">



回答3:


I found that as you set name and id attribute same of your function name causing this conflict and prompting error viewroom is not a function, change the name of function. also define your js at the bottom of document.

function viewRoom()
{
    alert(123);
}

Working Demo



来源:https://stackoverflow.com/questions/14919922/select-onchange-not-working-inside-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!