简体   繁体   中英

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.

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!");
});

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM