Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store field Id in a row?

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 ?

  • By using .data() function of jQuery ?
  • An hidden html element with the id as value (<span class="id">3</span>) ?
  • Other solution ?

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")
like image 912
Benoît Avatar asked Mar 16 '11 13:03

Benoît


4 Answers

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

like image 55
Mark Coleman Avatar answered Oct 17 '22 05:10

Mark Coleman


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.

like image 23
krtek Avatar answered Oct 17 '22 06:10

krtek


you can also use jQuery metadata .....

Its awesome to store data in html

like image 1
Avi Avatar answered Oct 17 '22 05:10

Avi


Instead of using id use data-id and use the .data('id') (on that element) to retrieve it with jQuery.

like image 1
Gabriele Petrioli Avatar answered Oct 17 '22 05:10

Gabriele Petrioli