0

Let's say I have a Table like this:

<table>
<tr>
<td>My House </td>
<td>My Car </td>
</tr>
</table>

And using jquery, if you clicked on one of them, I want it to show the value of that item. Is it okay practice to store additional information in an attribute like value for example and then fetch it using .attr()

Sam Creamer
  • 5,187
  • 13
  • 34
  • 49

4 Answers4

3

jQuery has .data() for applying data. There is also the data-xxxx attribute for storing data while keeping your HTML valid. Whatever method works better for you!

twinlakes
  • 9,438
  • 6
  • 31
  • 42
2

As long as you have an HTML5 Doctype the page will still validate and you can use data- attributes. See jQuery data and data attributes.

So with this markup:

<table id="data-table">
    <tr>
        <td data-value="house">My House </td>
        <td data-value="car">My Car </td>
    </tr>
</table>

Something like this:

$(function(){
    $('#data-table').on('click', 'td', function(){
        var val = $(this).data('value');
    });
});
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
1

Sure, you can do a bunch of things that way.

kevhann80
  • 311
  • 2
  • 6
1

You can do that, although best practice is to use some specific attributes names for it like rel or (even better) using data attributes.

Example using rel:

<td rel="123">My House</td>

Example using data (more JQuery friendly):

<td data-value="123">My House</td>

For this last example, instead of retrieving the value using JQuery's attr function, you can use this:

$(elem).data("value")

Also to set the value you do:

$(elem).data("value", "new_value")

You can have several data attributes in the same element.

Rafael Martinez
  • 772
  • 3
  • 11