0

I have a button where I am trying to add on click jquery as below

<button onclick="myFunction()">YES</button>

And

$(document).ready(function() {
    function myFunction(){
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");        
    }
})

However, on click I am getting Uncaught ReferenceError: myFunction is not defined

What am I doing wrong and how to fix this?

Updated with a sample jsfiddle

http://jsfiddle.net/3aC7W/1/

2
  • You havent included jQuery in your fiddle. Commented Jan 24, 2014 at 4:55
  • You cannot access the function inside another function globally. you have to make your inner function globally like window.myFunction = function () { alert('It works now'); } Commented Jan 24, 2014 at 4:59

3 Answers 3

4

What am I doing wrong and how to fix this?

You are defining the function inside another function, i.e. the function is not defined in global scope and hence cannot be found by the inline event handler.

Just remove $(document).ready(function() { because you don't need it there:

function myFunction(){
    $('#mycheckboxdiv').toggle();
    $("div#headersteptwo").addClass("hidden");        
}

You only have to use $(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document.


The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers):

$(document).ready(function() {
    $('button').on('click', function(){
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");        
    });
});

You might have to add a class or ID to the button to make the selector more specific. Have a look at the list of available selectors.

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

1 Comment

Note that in your fiddle, the JavaScript code is already placed inside a ready event handler. You also have to change the option from onLoad to no wrap.
1

change your code to this way to achieve click :

<button id="myFunction">YES</button>

and

$(document).ready(function() {
    $('#myFunction').click(function(e){
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");
    });
});

check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/

Comments

0

change your code to this:

$(document).ready(function() {
    window.myFunction = function(){  //you should make myFunction avaliable in global
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");        
    }
})

Comments

Your Answer

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