Reputation: 145
I am trying to alert out individual id of every user on the user link click in html. So, every user is being fetched from the database and displayed on the page as a link. Also, since they have a unique email id, I am trying to alert out their emails when that user link is clicked. My issue is whenever I click on the first one, it alerts out the email, but the second, third or so on, on clicking does not pop up any alert.
Here is a snippet of the code :
<strong><a href="#" id="post_user" name="post_user" class="<?php echo $messagePost_Email; ?>"><?php echo $messagePost_FirstName.' '.$messagePost_LastName;?></a></strong>
Jquery
<script type="text/javascript">
$(function(){
$("#post_user").click(function(){
var element = $(this);
var emailID = element.attr("class");
var info = "emailID="+emailID;
alert(info);
$.ajax({
tpye : "POST",
url : "navigate.php",
data: info,
success : function(){
}
})
})
})
</script>
Any suggestions would be of great help since I am not able to figure out the root cause of this behaviour.
Upvotes: 1
Views: 72
Reputation: 189
try this way
<script src="jquery.min.js"></script>
<strong><a href="#" id="post_user1" name='[email protected]'>user1</a></strong>
<strong><a href="#" id="post_user2" name='[email protected]'>user2</a></strong>
<strong><a href="#" id="post_user3" name='[email protected]'>user3</a></strong>
<script type="text/javascript">
$("a").click(function(event){
// Capture the href from the selected link...
ids = ['post_user1', 'post_user2'];//add anchor id, at which you want to call this function.
var id = this.id;
if($.inArray( id, ids ) != -1) {// check this id is in list.
var email = this.name;
var info = "emailID="+email;
alert(email);
$.ajax({
tpye : "POST",
url : "navigate.php",
data: info,
success : function(){
}
});
}
return false; // not needed if you want the link to execute normally...
});
</script>
Upvotes: 0
Reputation: 9157
The issue is that you're probably using the same id
attribute for every anchor element:
<strong><a href="#" id="post_user" ...
The id
attribute is meant to be an identifier and as such must be unique.
You should get rid of the id
attribute (if you don't use it elsewhere) and as a jQuery selector use class
instead. Eg:
<strong><a href="#" class="post_user" ...
The emailID
(your user id) store in a data
attribute of the element as it's more clear way of doing such things. This is what the data
attribute is best to use for.
<a href="#" class="post_user" data-emailID="<?php echo $messagePost_Email; ?>" ...
jQuery:
$(function(){
$(".post_user").click(function(){
var emailID = $(this).attr("data-emailID");
// or:
// emailID = $(this).data("emailID");
alert(emailID);
$.ajax({
type : "POST",
url : "navigate.php",
data : {emailID : emailID},
success : function(response){
// ... do anything with "response" ...
}
})
})
})
Upvotes: 1