1

I find a lot of situations where I'd like to attach a variable to a div or another HTML element. For example, I have a div that I'm using as a dialog window to edit a row in a table - something like this:

    <div class='dialog' id='editTableLineDialog'/>

When this dialog opens, I need to record the id of the line in the table I'm editing. In the past I've created global variables called lineCurrentlyEditting (Yuck!) or I've embedded the id in the actual table id like such:

    <div class='dialog' id='editTableLineDialog_43'/>

Neither solution is very elegant. I'd like to be able to just add the variable to the div, like such:

    var dialog = document.getElementById('editTableLineDialog');
    dialog.tableLineId = 43;

or

    $('#editTableLineDialog').tableLineId = 43;

or

    <div meta='{tableLineId=43}' class='dialog' id='editTableLineDialog'/>

Is there anyway to do something like this? What's the best way to handle a situation like this? Does JQuery have a solution?

dallin
  • 8,775
  • 2
  • 36
  • 41
  • 2
    You're using jQuery, so use [`.data()`](http://api.jquery.com/data/): `$('editTableLineDialog').data('tableLineId', 43);` – gen_Eric Jul 18 '13 at 18:53
  • Your first soultion `dialog.tableLineId = 43;` will work fine, and is very fast and efficient. I'd probably not store large objects, but numbers and such are fine. –  Jul 18 '13 at 18:55
  • Check this answer. You can add as an attribute. I dont know if it can handle something fancier. [Link](http://stackoverflow.com/questions/710275/how-to-add-update-an-attribute-to-an-html-element-using-javascript) – wendelbsilva Jul 18 '13 at 18:57
  • i would use a non-attrib property, like tableLineId. that will be MUCH faster than setting a dom-reflecting property like dataset.x, className, title, or id. unless you need to persist the value in saved markup, an attrib is a waste of CPU and RAM. – dandavis Jul 18 '13 at 19:00

2 Answers2

9

You can use data attributes.

<div data-tableLineId='43' class='dialog' id='editTableLineDialog'/>

jQuery has a data function: (http://api.jquery.com/jQuery.data/)

$.data('#editTableLineDialog', 'tableLineId','43');
Barbara Laird
  • 12,599
  • 2
  • 44
  • 57
2

Common practice is to store values like that in what's called a "hidden field". Presuming the dialog is in the same page as the table, you could very well just have something like this:

<input type="hidden" id="tableRowEdited" value="43">

That won't be rendered to the user, but you can then refer to it via jQuery:

$("#tableRowEdited").val()
Jim Dagg
  • 2,044
  • 22
  • 29