Reputation: 180
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!
Upvotes: 1
Views: 11110
Reputation: 12073
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")};
Upvotes: 1
Reputation: 82267
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");
};
}
Upvotes: 3
Reputation: 15860
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");
}
Upvotes: 1