Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call jQuery on buttonclick

Tags:

jquery

I'm trying to run some jQuery code when I click a button, but I can't make even the most simple example work.

My jQuery code is this:

<script src="scripts/jquery-1.4.1.js"></script>
<script>
    $('#btn').click(function() {
        alert("Hello");
    });

</script>

and my html looks like this

<div>
    <input id="btn" type="button" value="button" />
</div>

but when I click the button nothing happens.

like image 610
KristianMedK Avatar asked Dec 20 '12 14:12

KristianMedK


1 Answers

wrap your code inside a document.ready function

$(function(){
    $('#btn').click(function() {
        alert("Hello");
    });
});

or put your script code right before the end of the body tag

You need to wait for the elements to be available the dom on page load before binding event handlers

like image 146
wirey00 Avatar answered Oct 27 '22 13:10

wirey00