Click here to Skip to main content
15,901,368 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Hi everyone,

I'm currently working on a webpage that requires me to have a button, that will run a simple JQuery function that is held on a separate .js file.
I have the script in my head section of the page, so there is a link to the function, I just need to find out how to run it using a button!

Any comments are greatly appreciated thankyou!

Tom.
Posted

Hi,

It's simple...
Your button must have some id and you only need to add a few lines of code to attach click event handler to that button...

It will look something like this:
HTML
<script type="text/javascript">

        $(document).ready(function(){
                $("#btn").click(function(){
                        //YourFunctionNameInExternalFile();
                });
        });

</script>

<!-- Simple button  -->
<input type="button" id="btn" value="Click" /> 
 
Share this answer
 
Have a look at the onclick event[^]

You could call your jQuery function (or any other script function) directly from the button onclick event if you want

Or, using a jQuery flavoured approach, you can attach event handlers to your button and have them execute - you'd need to attach the handlers during the document ready function


http://api.jquery.com/click/[^]

JavaScript
$(document).ready(function() {
    $("#yourButtonId").click(function() {
      // Something that happens when you button is clicked
    });
});


Just add the document.ready code as above within some script tags on the page you want it to execute
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900