Reputation: 3797
This looks very simple but I have little experience with jQuery and I can't wrap my head around it.
Let's say I have a dynamically generated HTML table, and in each row of this table is a link:
<a id='edit'>Edit User</a>
Now, the link should call a function with each user's ID as a parameter. I could do that inline liek this:
<a id='edit' onClick='editUser(<?php echo $row['id']; ?>)'>Edit User</a>
But how do I do this in jQuery?
I can call the function like this:
$('a#edit').click(function () {
editUser()
return false;
});
But how do I pass the ID to this function? I know I could first stick it into a hidden field and then get it from there by element id, but surely there's a better way?
I realize all the links would have the same id this way, so should I dynamically create the link ids by appending the user id? But then how do I call the jQuery?
Upvotes: 4
Views: 889
Reputation: 1215
As Curt mentionned, the data-id
is the way to go, if you're using HTML5. If you're using HTML4, I would pass this in the ID of the link :
<a id='edit-321' class='edit'>Edit User</a>
Then you can do this (and use event.preventDefault()
rather than return false
!) :
$('a.edit').click(function (evt) {
editUser($(this).attr("id").substring(5));
evt.preventDefault();
});
Upvotes: 0
Reputation: 103358
Use data-*
attributes to pass parameters.
<a class='edit' data-id='<?php echo $row['id']; ?>'>Edit User</a>
$('a.edit').click(function () {
editUser($(this).data("id"));
return false;
});
Upvotes: 2
Reputation: 1038810
ids must be unique throughout the entire HTML. So you could use a class selector and HTML5 data-* attribute:
<a class="edit" data-id="<?php echo $row['id']; ?>">Edit User</a>
and then:
$('a.edit').click(function () {
var id = $(this).data('id');
// do something with the id
return false;
});
Upvotes: 8