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?
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;
});
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With