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!
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!
Share Improve this question asked Mar 19, 2014 at 18:43 jligdajligda 1801 gold badge3 silver badges18 bronze badges3 Answers
Reset to default 3That 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");
};
}
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