0

I have the following HTML Code.

 <select onChange="TestCall()">
<option>Text1</option>
<option>Text2</option>
<option>Text3</option>
<option>Text4</option>
</select>

My JavaScript have a simple alert message like below.

 function TestCall()
{
 alert("Test");
}

Check the following Jsfiddle. I have added my script in the javascript area of jsfiddle. It is not working.

JSFIDDLE NOT WORKING HERE

But If i move script block inside the HTML area of jsfiddle is working. Check the below one.

JSFIDDLE WORKING HERE

What wrong in my code? Any Idea?

2
  • jsfiddle.net/Q9ukX/2 - On the 2nd dropdown under Frameworks & Extensions, choose No wrap in <head> or <body> Commented Jun 2, 2014 at 11:21
  • Don't apply listeners like this. It is annoying and not maintainable. element.addEventListener('change', TestCall, false); Commented Jun 2, 2014 at 11:33

2 Answers 2

4

By default JSFiddle wraps the JS block into onLoad function:

... leading to something like:

window.onload = function() {
    function TestCall() {
        alert("Test");
    }
};

This means that your TestCall method is getting out of global scope and is not accessible from HTML attributes.

Change the option to No wrap - in <head> or No wrap - in <body> and it will work.

DEMO: http://jsfiddle.net/Q9ukX/3/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks VisioN. But why it is not working in "onDomready" selection also?
@SureshPonnukalai Same reason: the code gets wrapped in onDomReady function and is getting out of global scope.
2

Fiddle

It works if you change the settings down the side.

Change it from onLoad to No Wrap - in body or No Wrap - in head.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.