Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery function for multiple button event with same Id

I am trying to call a JQuery function to occur fade in event for the buttons with same id, but it seems only first button in the brower can occur the event.

This is JQuery Function to "fade in" for buttons with Id="skip". Once click the button(Id="next"), other button(Id=skip) is doing fade in.

$(document).ready(function () {
    $('button[id^="next"]').click(function () {
        $("#skip").hide().fadeIn(5000);
    });
});

This is the button id="next"

 <button id="next" type="submit" value="2" name="submit">Next</button>

And This is button id="skip"

<div id="skip">
<form method="post" >
<input type="hidden" id="skip_ig" name="skip_ig" value=""></input>
<div id="fade"><button type="submit" value="3" name="submit">Skip >></button></div>
<?php include('includes/aftersubmit.php');
</form>
</div>

I have multiple buttons of these "next" and "skip". But only first "skip" button does fade-in, others are not. Is Jquery function can only call first button when there are multiple button with same id? Thank you for your help.

like image 483
Taewan Avatar asked Jun 12 '13 18:06

Taewan


2 Answers

This is asked about a dozen times a day. The ID attribute must be unique within your document. You cannot have multiple elements with the same ID. This is undefined behaviour which typically manifests as only the first element being selected (presumably, at the browser level, subsequent duplicate IDs are ignored).

like image 166
meagar Avatar answered Nov 02 '22 08:11

meagar


You're using your attributes wrong. ID attributes should only be used once and should be unique. If you want multiple instances with the same identifier you should be using class attributes so instead of having

id="next"

you should have

class="next"

then just use the class selector as in

$(".next").click( function() {
    ...
});

and it should work for all of them

like image 32
Ian Avatar answered Nov 02 '22 06:11

Ian