Question

Could someone tell me why this is not working?

<!DOCTYPE html>
<html>
<head>
<script>
window.onload = initPage;

function initPage() {
    document.getElementById("member_type_academic_4").onChange=alert("It's Working");
}
</script>
</head>
<body>

<form>
  <label for="member_type_academic_4">test</label>
  <select name="member_type_academic_4" id="member_type_academic_4">
    <option value="0" selected>Select One</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
  </select>
</form>

</body>
</html>

It will fire the alert box when the window loads, but not when there is a change on the select box. I know it's something simple that I'm missing. Thanks!

Was it helpful?

Solution

That is because the onchange event handler is assigned the return value of the method call to alert. This ends up being undefined, however, calling alert will send the message to the screen. Instead you should use a function to assign to the event handler

function initPage() {
 document.getElementById("member_type_academic_4").onchange = function(){
  alert("It's Working");
 };
}

OTHER TIPS

Why not execute the function when there is actually a change in the select element?

<select name="member_type_academic_4" onchange="initPage()"
id="member_type_academic_4">
    <option value="0" selected>Select One</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

Then change the Function to this one:

function initPage() {
    alert("It's Working");
}

First: "onChange" -> "onchange"

Next, wrap the alert function in a wrapper, otherwise it will just execute as soon as it is encountered in the code.

document.getElementById("member_type_academic_4").onchange=function(){alert("It's Working")};

A jsFiddle for you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top