I would like to move all Javascript from HTML markup into separate files but I’m still fighting with the following:
Let’s say I have a table with many rows (users table) and for every user I need a button to call a function. Now I do this for every row:
<button onClick='doSomething(a,b,c);'>Edit</button>
I know I can use a class attribute to tell for example jQuery that all the buttons with some class should call a javascript function doSometing. However I don’t know how to pass parameters (a,b,c) to that function. These parameters, as I expect, must be on every row in the table, but where to put them?
Just a note: a,b,c are different for every row. Example:
<tr>
<td>1</td>
<td>John</td>
<td><button onclick="doSomething(1,3,5);">Work!</button></td>
</tr>
<tr>
<td>2</td>
<td>Merry</td>
<td><button onclick="doSomething(2,7,9);">Work!</button></td>
</tr>
Thanks!
One way would be simply place the values in a hidden field.
Where each
,is a value for the function. In your jQuery click you can use.siblings(.values)Now if you are using jQuery 1.4.3 or greater jQuery will automatically parse
data-*attributes. Things become a bunch easier.This allows you to store a value or even a complex json object in this data-* attribute and jQuery will parse it automatically.
Code example on jsfiddle