Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: pass arguments to onclick handler

I need to pass extra arguments to onclick handler. I can't decide which way is "better":

EDIT:
Context: I have a table that shows roster of an event. Each row has a 'delete' button. What is a better way to pass recordId to the delete-handler?

$('a.button').click(function() {
    var recordId = $(this).metadata().recordId;
    console.log(recordId);
});
...
<tr>...<a class='{recordId:1} button'>delete</a></tr>
<tr>...<a class='{recordId:2} button'>delete</a></tr>

or

function delete(recordId) {
    console.log(recordId);
}
...
<tr>....<a class='button' onclick='deleteRecord(1)'>Delete</a></tr>
<tr>....<a class='button' onclick='deleteRecord(2)'>Delete</a></tr>

What are the pros and cons for each option?

NOTE: I use a.button as a custom, CSS-styled button, it does not behave as a link.

EDIT:
I would appreciate alternative solutions as well, if you can argument the advantages of offered alternatives.

like image 355
THX-1138 Avatar asked Mar 02 '26 15:03

THX-1138


2 Answers

Store the record id as an attribute of element itself, but instead of using the metadata plugin which stores it in a weird format, I would recommend you use HTML5's data attributes that is also backwards compatible.

A row would look like:

<tr> .. <a data-id="1">delete</a> .. </tr>

In the handler, retrieve the attribute value and act on it

function deleteRecord() {
    var rowId = $(this).attr('data-id');
    ...
}

It is comparable to using the metadata plugin, but it does not overload the class attribute. No extra plugins are needed for this. It uses a single handler just as the metadata plugin does which is performant for large datasets.

The inline onclick handlers are bad for the same reasons. A new handler is created per row. It cuts down on flexibility and is generally a bad practice.

like image 193
Anurag Avatar answered Mar 04 '26 04:03

Anurag


I would just go with your second approach - it's the simplest and there is nothing wrong with it.

like image 33
serg Avatar answered Mar 04 '26 05:03

serg