0

i can't understand why this code works well

but the code below no.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>


<script type="text/javascript">
$('#enviar').click(function(){
    alert ("casd");
});

</script>

</head>
<body>

    <input type="submit" id="enviar" value="Registo" />

</body>
</html>

what is the reason?

3
  • 1
    What happens? What errors do you get? Commented May 26, 2011 at 23:08
  • no errors. nothing happens when i click in the button. Tested in FF4 and chrome Commented May 26, 2011 at 23:09
  • 1
    I can tell you why the jsfiddle works: If you look in the upper left corner you see a select box where it says onLoad. That means the JavaScript code is executed after the whole page loaded. Your code is the same as selecting no wrap (head) and you will see that it won't work either. Commented May 26, 2011 at 23:15

2 Answers 2

4

The handler is being attached before the element even exists. Either switch to $.live() or run your code on document ready:

$(function(){
  // attach click here
});

This will cause the code to wait until the document has loaded, and your #enviar element exists within the DOM. Until it exists, nothing can be attached to it.

Sign up to request clarification or add additional context in comments.

Comments

2

When you attach the click event handler the document has not loaded yet. That is the < input > element is not available in that state.

The solution is to attach the handler after the document has loaded by using the jquery ready function like this:

$(document).ready(function(){
    $('#enviar').click(function(){
    alert ("casd");
});

Comments

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.