Taewan
Taewan

Reputation: 1227

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.

Upvotes: 5

Views: 39037

Answers (3)

jk.
jk.

Reputation: 14435

Maybe something like this is what you want:

<button class="next" type="submit" value="2" name="submit">Next</button>
<div class="skip">
    <form method="post" >
        <input type="hidden" class="skip_ig" name="skip_ig" value=""></input>
        <div class="fade"><button type="submit" value="3" name="submit">Skip >></button> </div>
        Stuff here
    </form>
</div>


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

http://jsfiddle.net/tHcan/

Upvotes: 1

user229044
user229044

Reputation: 239551

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).

Upvotes: 24

Ian
Ian

Reputation: 326

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

Upvotes: 20

Related Questions