Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter to jQuery function?

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?

like image 243
sveti petar Avatar asked Dec 28 '22 01:12

sveti petar


2 Answers

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;
});
like image 80
Darin Dimitrov Avatar answered Jan 07 '23 15:01

Darin Dimitrov


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;
});
like image 25
Curtis Avatar answered Jan 07 '23 17:01

Curtis