最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript onChange for Form Select Field - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 3

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");
 };
}

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

发布评论

评论列表(0)

  1. 暂无评论