Reputation: 23989
I have a page which allows a user to 'nudge' someone to do something
I have the following html (it can appear many times but I'll show two for now)
<div class="nudgeHolder641">
<a id="nudge" data-wl_id="641" data-nudge_for="415" data-nudge_from="63" href="#">Nudge</a>
</div>
<div class="nudgeHolder1172">
<a id="nudge" data-wl_id="1172" data-nudge_for="415" data-nudge_from="63" href="#">Nudge</a>
</div>
I have the following code to action the click:
$(document).ready(function(){
$("#nudge").click(function() {
var nudge_from = $( '#nudge' ).data( 'nudge_from' );
var nudge_for = $( '#nudge' ).data( 'nudge_for' );
var wl_id = $( '#nudge' ).data( 'wl_id' );
var dataString = 'nudge_from='+ nudge_from + '&nudge_for=' + nudge_for + '&wl_id=' + wl_id;
$.ajax({
type: "POST",
url: "/pages/includes/ajax/nudge.php",
data: dataString,
success: function() {
$('.nudgeHolder'+wl_id).html("<h3>Fantastic!</h3>")
.append("<p>Nudge Sent!</p>")
.hide()
.fadeIn(1500, function() {
//$('#message').append("<img id='checkmark' src='/images/icons/check.png' />");
});
}
});
return false;
});
});
Only the first instance of the link fires when clicked though, when I click the second 'nudge' link nothing happens, the first one works as it should. If there is only one link shown on a page then it works fine.
Any ideas?
Upvotes: 0
Views: 361
Reputation: 80639
Rather than having unique div
classes, use them as ID on a
tag. Like this:
<div class="nudge">
<a id="nudgeHolder641" data-wl_id="641" data-nudge_for="415" data-nudge_from="63" href="#">Nudge</a>
</div>
<div class="nudge">
<a id="nudgeHolder1172" data-wl_id="1172" data-nudge_for="415" data-nudge_from="63" href="#">Nudge</a>
</div>
And then, in jQuery; you need:
$(document).ready(function(){
$(".nudge a").click(function() {
Didn't notice that you were using $('#nudge')
everywhere. As ryadavilli pointed out; replace $('#nudge')
to $(this)
.
Upvotes: 0
Reputation: 53198
You're binding to an ID, and an ID can only exist once in the DOM. Try changing it to the class:
<div class="nudgeHolder641">
<a class="nudge" data-wl_id="641" data-nudge_for="415" data-nudge_from="63" href="#">Nudge</a>
</div>
<div class="nudgeHolder1172">
<a class="nudge" data-wl_id="1172" data-nudge_for="415" data-nudge_from="63" href="#">Nudge</a>
</div>
And then bind using:
$(function(){
$(".nudge").click(function() {
var nudge_from = $( this ).data( 'nudge_from' );
var nudge_for = $( this ).data( 'nudge_for' );
var wl_id = $( this ).data( 'wl_id' );
var dataString = 'nudge_from='+ nudge_from + '&nudge_for=' + nudge_for + '&wl_id=' + wl_id;
$.ajax({
type: "POST",
url: "/pages/includes/ajax/nudge.php",
data: dataString,
success: function() {
$('.nudgeHolder'+wl_id).html("<h3>Fantastic!</h3>")
.append("<p>Nudge Sent!</p>")
.hide()
.fadeIn(1500, function() {
//$('#message').append("<img id='checkmark' src='/images/icons/check.png' />");
});
}
});
return false;
});
});
Upvotes: 6