Vignesh Pichamani
Vignesh Pichamani

Reputation: 8070

Perform click function on same id at more than once using jquery

NOTE: Sorry for Asking this type of question.

I have a form with save button on top and bottom. I make it as common id to perform the click function. For the first save button get the alert but for second save button contain same id only but the alert won't appear. I am not sure how to make the alert for the two button which contain same id.

  jQuery("#preview").click(function() {
            alert("Handler for .click() called.");
        });

Here is the fiddle. http://jsfiddle.net/N8Mhd/

Any suggestion would be great.

Upvotes: 1

Views: 1354

Answers (3)

Mato
Mato

Reputation: 416

You can't use two elements with same id, ids need to be unique. You should use classes:

<input type="button" class="preview" value="Click Me :)"/>

...

<input type="button" class="preview" value="Click Me :)"/>


<script>
jQuery(".preview").click(function() {
   alert("Handler for .click() called.");
});
</script>

Upvotes: 1

Joel Peltonen
Joel Peltonen

Reputation: 13442

IDs should be unique, do not use the same id for two elements. Use classes instead.

So just use

<input type="button" class="preview" value="Click Me :)"/>
<input type="button" class="preview" value="Click Me :)"/>

jQuery(".preview").click(function() {
    alert("Ponies!");
});

Upvotes: 2

Sachin
Sachin

Reputation: 40990

As Id can not be duplication so you can change the Id selector to class selector and then can bind the same event.

<input type="button" class="preview" value="Click Me :)"/>    
<input type="button" class="preview" value="Click Me :)"/>

Script:

jQuery(".preview").click(function() {
    alert("Handler for .click() called.");
});

jsFiddle Demo

Upvotes: 1

Related Questions