2

I have a simple page for testing with only a button, I am linking to an external js file. It is displaying the jquery version in a alert box, but when the button is clicked nothing happens. What is wrong with this?

Here is my simple test html page

<title>Insert title here</title>
<!-- scripts -->
<script language="JavaScript" type="text/javascript" src="jquery.js"></script>
<script language="JavaScript" type="text/javascript" src="myscript.js"></script>
</head>
<body>
<form>
    <input  type="button"  tabindex="5"  value="jscript" id="testbutton" />
</form>
</body>

and here is my myscript file content

alert($.fn.jquery);
$('#testbutton').click(function(){
alert("test successful");
});

I am using JQuery version 1.6

2 Answers 2

4

Probably because the DOM is not ready for JavaScript processing at the time of bindiing the click handler. Try:

$(document).ready(function() {
    $('#testbutton').click(function(){
        alert("test successful");
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

@Abhishek - Just to point out, I did answer first, but okay. (order the answers by oldest first) :)
sorry i did not see the time. Thanks again!
44 seconds makes all the difference! (+1 for both though) :)
1

You need a document.ready:

$(document).ready(function(){
  alert($.fn.jquery);
  $('#testbutton').click(function(){
    alert("test successful");
  });
});

That's because your #testbutton can't be referenced until it's loaded

Hope this helps. Cheers

2 Comments

Thanks it worked. so this .ready() function is required at least once i suppose?
Sorry Edgar, I did not see before but Karim79 answered my question 1st :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.