I write a web site with jquery and lot of ajax request to get data for table and ask data modifications with PHP/MySql on server side.
Currently, I use id attribute to store the id of the field of the table (which is an autoincrement int value).
And it works fine.
BUT I have recently learned that id should be unique (and start with a letter...).
AND I have different tables that could have the same id value (for different sql table)
Then I am not html (nor xhtml) compliant...
How could I correct my code ?
.data()
function of jQuery ? <span class="id">3</span>
) ? Additional informations:
I have wrote a widget to manage my tables.
To add a new row, I do:
row = $('<div class="row" id="'+item.id+'"/>');
[...] // I add fields to my row
row.appendTo(tableData);// tableData is the html element where rows are
When a field element is changed, I trigger an event to the table that will ask the modification to the server with the right id:
$(e.target).closest(".row").attr("id")
If you are able to use jQuery 1.4.3 or greater look at using the html 5 data-*
attributes. jQuery 1.4.3 will automatically use those data- attributes and place them in the .data()
collection on the element.
Example:
<table>
<tr data-rowId="1">
</tr>
</table>
$("tr:first").data("rowId")
would print 1
This method would also allow you to store json objects as well.
<table>
<tr data-row='{"Id" : 1, "Name": "Smith"}'>
</tr>
</table>
And than in your data()
var row = $("tr:first").data("row")
You can reference row.Id
and row.Name
You can prefix your id with the table name :
<div id="mytable_1234"></div>
It's easy to extract the table name and the id from the field and this is HTML compliant.
var values = $(element).attr('id').split('_');
// values[0] is the table name and values[1] is the id.
You can use any other separator if you're already using underscores in your table names.
you can also use jQuery metadata .....
Its awesome to store data in html
Instead of using id
use data-id
and use the .data('id')
(on that element) to retrieve it with jQuery.
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