2

When building up a list of options in a select list using Javascript I'd like to attach a Javascript object to that option that I could easily retrieve in the change event.

So, while writing this question I wanted to provide some sample code and found a way to make this work; so I have a slight addition to the question. Is it bad to attach javascript object to DOM elements? Back in the day I remember there being issues with memory leaks in certain circumstances.

Here's a working example: http://jsbin.com/afolo3/edit

var objs = [
  { id: 1, value: "One", type: "number" },
  { id: 2, value: "Two", type: "number" },
  { id: 3, value: "Three", type: "number" },
  { id: "A", value: "A", type: "char" },
  { id: "B", value: "B", type: "char" },
  { id: "C", value: "C", type: "char" },
  ];

var options = $.map(objs, function(item, idx) {
  var opt = $("<option/>").val(item.id).text(item.value);
  opt[0]["obj"] = item;
  return opt;
});

$.fn.append.apply($("#select"), options)
  .change(function() {
    $("#select option:selected")
      .each(function(){
    alert(this.obj.type);
      });
  });
1
  • Don't think that your case will created memory leaks - unless if you are creating the element using JS code and then inserting it to the DOM. If you have the select element html code in place and just populate the options using JS i don't think that you will be having memory leaks Commented Oct 1, 2010 at 17:35

2 Answers 2

3

Use jQuery's .data() function instead.

Updated example: http://jsbin.com/afolo3/2

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for providing the link and changing the example.
1

You can certainly attach objects to element instances the way you have; in fact, that's how jQuery does its data magic behind-the-scenes in the current version.

That said, since you're using jQuery already, I'd probably use the jQuery API for this (data) instead, just in case it turns out that at some stage, a browser comes on the scene where a workaround is required — you'll get the benefit of the jQuery maintainers doing the workaround for you, rather than having to do it yourself.

Here's what it would look like using data. Basically to set the data:

opt.data("obj", item);

...and to retrieve and show its type property:

alert(opt.data("obj").type);

...where in each case, opt is a jQuery object for the option element in question.

One slight "gotcha" with jQuery's data function: If you retrieve a data object you've never set, you'll get null back (rather than undefined, which would be the usual JavaScript convention).

1 Comment

Great!, that's exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.