简体   繁体   中英

onclick function need to execute a simple javascript function

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/

What am I doing wrong and how to fix this?

You are defining the function inside another function, ie 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 .

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/

change your code to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM