I'm trying to keep a strict separation of javascript with html merging together and my current issue is that I have multiple html tables on a page, whenever you click on a box in the table it is editable and should on clicking off the box update the table sending the information to the SQL database dynamically.
Now my issue is that the way I currently have it doing it which is inside the html row is not something I'm a fan of as shown below:
onblur="update_table(this, 'column name', 'row id', 'sql table name')"
I'm trying to work out how I can give the function this information without passing it through directly as variables into the function.
So rather than having a trigger onblur, have a listener in the javascript, something like this:
$('.A Class Name for rows or something').on('blur', function () {
My thought process is that I should have a specific class name that all rows have so that it listens in on that class name? Now I'm just wondering how I get the information from the row like column name, row id and what sql table it needs to go to.
Please let me know if this doesn't make sense!
To add metadata to an element you can use data attributes. Then you can read those from the element when the event occurs on it. Try this:
<input type="text" class="foo" data-columnname="column name" data-rowid="row id" data-sqltablename="sql table name" />
$('.foo').on('blur', function() {
var $el = $(this);
update_table(this, $el.data('columnname'), $el.data('rowid'), $el.data('sqltablename'));
});
It's also worth noting that there's a couple of potential code smells here. Firstly, either pass the element reference (ie. this) to the function or the relevant properties, not both. Secondly, requiring both the 'table name' and 'column name' in the client-side function is a little odd. It's also potentially an attack vector exposing this information to any user viewing the site.
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