priyabrata
priyabrata

Reputation: 169

how to call a function from an external file link to the main file

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

Upvotes: 0

Views: 762

Answers (3)

DontVoteMeDown
DontVoteMeDown

Reputation: 21475

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.

Upvotes: 1

Wout De Rooms
Wout De Rooms

Reputation: 657

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>

Upvotes: 0

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11611

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(){
        // ...
    });
});

Upvotes: 1

Related Questions