select onChange not working inside a form
Asked Answered
I

5

12

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>
Immingle answered 17/2, 2013 at 9:59 Comment(0)
P
21

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

Painful answered 17/2, 2013 at 10:5 Comment(4)
Also interestingly, if I move the select statements outside of the form, then the onChange event works without a problem. (is this normal or just I get lucky?)Immingle
Unfortenately I don't know, the code seems to work exactly you desrcibed.Painful
This wasn't exactly my issue, but I did have a naming conflict. Points for steering me in a good direction. Thanks!Halsey
Awesome! Thanks!Mcclintock
G
5

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()">
Glaikit answered 17/2, 2013 at 10:6 Comment(1)
interesting restriction! thanksLeucite
G
2

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

Gouge answered 17/2, 2013 at 10:12 Comment(0)
D
0

Change

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

to

<select name="viewroom" id="viewroom" onChange="()=>viewroom()">
Disassembly answered 12/6, 2020 at 15:31 Comment(0)
B
0

Just to bring some tip, not for this case, someone may have added a new and different function that killed the old one.

<select ... onchange="anOldFuncion()">

And in javascript later you did:

selectX.onchange = function(){};  //bye bye function from the tag.

The naming in this code is terrible. I would have choosen:

<select name="viewroom" id="viewroom" onChange="selectRoom()">
Butters answered 16/7, 2022 at 21:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.