admin管理员组

文章数量:1310254

I'm trying to create an onchange event using javascript on a select element. But its not working, any hint what I'm doing wrong?

Script..

<script type="text/javascript">
function check() {
   alert("Hi");
}
</script>

HTML..

<body> 
<select name="selTitle" id="titles" onchange="check();">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>
</body>

Demo - /

I'm trying to create an onchange event using javascript on a select element. But its not working, any hint what I'm doing wrong?

Script..

<script type="text/javascript">
function check() {
   alert("Hi");
}
</script>

HTML..

<body> 
<select name="selTitle" id="titles" onchange="check();">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>
</body>

Demo - http://jsfiddle/jq9UA/1/

Share Improve this question edited Oct 28, 2011 at 18:06 asked Oct 28, 2011 at 18:01 user963395user963395 3
  • Where does the script merge with your HTML document? – Michael Sazonov Commented Oct 28, 2011 at 18:04
  • your provided code worked for me. I haven't included script in header tag. – Vikas Naranje Commented Oct 28, 2011 at 18:11
  • @Vikas- Don't know why is it so. For me it works only when the script is inside head. – user963395 Commented Oct 28, 2011 at 18:15
Add a ment  | 

2 Answers 2

Reset to default 6

The problem in the Fiddle is that the JavaScript code is running in response to the window load event (default on fiddle). Any code you run is defined in the context of the load call back and not at the global scope. If you look through the actual generated HTML for the frame you will find it looks like this

$(window).load(function(){
    function check() {
     alert("Hi");
  }

});

This means your code defines a check function which is local to the load callback but the event handler wants to invoke a globally defined check function.

To fix this you need to use one of the fiddle settings that defines the JavaScript in a global context. Try "no wrap (head)".

Fiddle: http://jsfiddle/jq9UA/3/

I have tested this and works perfectly fine:

<script name="text/javascript">
    function check() {
      alert("Hi");
    }
</script>    

<body>
<select name="selTitle" id="titles" onchange="check();">
<option value="Mr." value="1">Mr.</option>
<option value="Ms." value="2">Ms.</option>
</select>
</body>

本文标签: htmlJavascript onchange select not workingStack Overflow