0

i want to call a function from an external file but it shows it is undefined what i tried so far is

index.html file

<button class="btn btn-primary" onclick="check()" >click</button>

script.js file

$(document).ready(function(){ 
    function check()
 {

alert('checked');
 }


 });//document ready function

I would like to call the javascript file onClick of a button in the index.html.when i clicked on click button it shows check is not defined.what is the problem

priyabrata
  • 179
  • 15

3 Answers3

1

When you linked jQuery in your page (I got it, because you use $ sign), it's not good idea using onClick on html tag. I recommended you add class or id to the button and handle the click event with jQuery, like this:

$(function(){
    $('.CLASS_NAME').on('click', function(){
        // ...
    });

    // OR
    $('#BUTTON_ID').on('click', function(){
        // ...
    });
});
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
1

This is because your function was declared inside a scope which the button event can't reach. The button event can only reach at global functions or vars in the way you're using. Besides, don't use onclick in the element itself, you have to bind it, like @Mehdi said:

<button class="btn btn-primary check">click</button>

The JS:

$(document).ready(function() { 
    $(".check").on("click", function() {
       // Perform your check here.
    });
});

Or even better Or you can always do this:

$('body').on('click', '.check', function() {
    // Perform your check here.
});

But I don't think that it is your case.

Community
  • 1
  • 1
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • 1
    Bound event on body for this solution! it's not good idea http://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document – Mehdi Dehghani Aug 14 '15 at 18:07
  • @MehdiDehghani sure. I updated it. In case of just one element it isn't right, actually. But in case of many elements, or even dynamically created elements, it is a good practice. I was just trying to show different scope uses. – DontVoteMeDown Aug 14 '15 at 18:14
  • Yes, for dynamically created elements is true way, (of course I think for dynamically created elements, if we bound on closest static parent is better that bound on body) – Mehdi Dehghani Aug 15 '15 at 05:59
0

Either the document hasn't finished loading yet, so this function is not declared yet by the time you click it, but I highly doubt that.

More likely you forgot to add the external script to your html. And you also have to include jQuery since you are using it ($ = jQuery). Your html should look something like:

<html>
  <head>
    <title>Title of your page</title>
    <script src="https://code.jquery.com/jquery-1.11.3.min.js" />
    <script src="path/to/your/script.js" />
  </head>
  <body>
    <button class="btn btn-primary" onclick="check()" >click</button>
  </body>
</html>
Wout De Rooms
  • 647
  • 4
  • 10