views:

42

answers:

3

I am learning jquery and I am having difficulty to run the following extremely simple code.

My HTML looks like:

<html>
<head>
    <title>JQUERY</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript" src="script.js"></script>
</head>
<body>

<input type="button" id="testbutton" value="test" />

</body>

My script.js looks like this:

$(document).ready(function(){
  alert('document is ready');
});
$('#testbutton').click(function(){
  alert('button clicked');
});

when I load the page in browser ... I get the first alert when the document is loaded (so I am sure that I am atleast using the correct library and it is getting downloaded etc).

However when I click my button I do not see the second alert that says "button has been clicked"

What am I missing??

+3  A: 

The click handler needs to go inside your $(document).ready, to ensure that it is bound when the DOM is ready, and the element is guaranteed to be available for Javascript processing:

$(document).ready(function(){
    alert('document is ready');

    // bind a click handler to #testbutton when the DOM has loaded
    $('#testbutton').click(function(){
      alert('button clicked');
    });
});

From the documentation:

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

karim79
+1  A: 

You probably want to bind your event handler inside the $(document).ready() event:

$(document).ready(function(){
  alert('document is ready');

  $('#testbutton').click(function(){
   alert('button clicked');
  });
});

This makes sure the DOM is loaded before your other script gets executed. See if this solves your problem.

RMorrisey
+1  A: 

You also need that click binding inside a document.ready, like this:

$(function(){      //short for $(document).ready(function(){
  alert('document is ready');
  $('#testbutton').click(function(){
    alert('button clicked');
  });
});

The why? is that the selector $('#testbutton') won't find the element id="testbutton" if it's not ready when the selector runs, so it needs to be run after the element in the page, or in a document.ready handler like above.

Nick Craver