Dave
Dave

Reputation: 59

Multiple buttns on a page - not working

Can someone tell me why the following is not working?

<head>
<script language="javascript" src="/assets/js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$("button").bind("click", function() {
    alert("You clicked " + $(this).attr("id"));
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<button id="button1">Click Me!</button>&nbsp;<button id="button2">Click Me!</button>&nbsp;<button id="button3">Click Me!</button>&nbsp;<button id="button4">Click Me!</button>&nbsp;<button id="button5">Click Me!</button>
</body>

Nothing is happening when I click on any of the buttons.

Dave

Upvotes: 0

Views: 79

Answers (4)

Alex Bagnolini
Alex Bagnolini

Reputation: 22412

Try:

 $(document).ready(function() {
    $("button").bind("click", function() {
       alert("You clicked " + $(this).attr("id"));
    });
 });

Edit: As stated by Alex Sexton, the use of live instead of bind is also preferable when you have to apply the same function to more than 2 elements of the same type.
Follow the link for more infos, credits to him.

Upvotes: 5

Alex Sexton
Alex Sexton

Reputation: 10451

Another solution would be to use event delegation, so it doesn't matter that the buttons don't exist yet.

$("button").live("click", function() {
    alert("You clicked " + $(this).attr("id"));
});

Upvotes: 1

giolekva
giolekva

Reputation: 1178

Because your javasript code is executed before html body is loaded. You should call your JS after html is fully loaded. You can do it so:

$(function() { // it's called when document loads
    $("button").bind("click", function() {
        alert("You clicked " + $(this).attr("id"));
    });
});

But it's good practice not to inject your code into global scope. You can do it so:

(function() { // it helps you not to inject your code into global scope
    $(function() { // it's called when document loads
        $("button").bind("click", function() {
            alert("You clicked " + $(this).attr("id"));
        });
    });
})();

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039248

You need to bind the click handler when the DOM is ready:

$(function() {
    $("button").bind("click", function() {
        alert("You clicked " + $(this).attr("id"));
    });
});

Upvotes: 1

Related Questions