jquery <a> tag click event
I am building a code which displays user information on search. User information, is then displayed in a fieldset
, and a image, first name, last name and few profile info. is shown, and in the bottom of the fieldset
, there's a add as friend hyperlink:
<a href="#" id="aaf">add as friend</a>
Now I want to use jquery $post()
method to interact with another page. I also have a hidden field inside that user fieldset
which has the user id value. Now, when i create a click functionality using jquery
, i am not able to access the different hidden field values. Now i want to know how to achieve this functionality? For checking if i can get the value of hidden fields inside a set of code, i did this.
$(document).ready(function () {
$("a#aaf").bind('click', function () {
alert($("#uid").val());
});
});
But I'm only getting the value of first fieldset
, not others. Kindly guide me in this.
EDIT: How to get it in each tag click event? I'm putting some more code here,
<?php foreach($query->result() as $row){?>
<fieldset&开发者_Python百科gt;
<legend>
<?php echo $row->firstname.' '.$row->lastname;?>
</legend>
<img src='<?php echo $row->profile_img_url;?>'/><br>
<a href="#" id="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' id="uid">
</fieldset>
<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).attr("id");
//post code
})
//other method is to use the data attribute
<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).data("id");
var username = $(this).data("username");
})
That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid
and grab them via:
var uids = $(".uid").map(function() {
return this.value;
}).get();
Demo: http://jsfiddle.net/karim79/FtcnJ/
EDIT: say your output looks like the following (notice, IDs have changed to classes)
<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>
You can target the 'uid' relative to the clicked anchor like this:
$("a.aaf").click(function() {
alert($(this).next('.uid').val());
});
Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.
All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.
精彩评论