I have a <select> form element where I create multiple <option> children based on looping through a jQuery array of objects.
I want to store each jQuery associated with an <option> on the <option> itself, I guess as a property. So that when I get the change event fired I can pull out the jQuery object which the <option> was based on.
I thought I could just set it using attr, serializing the object into JSON, but its not working. Any ideas?
Here is some code:
// creating the select: (data is a jquery array of objects)
$(data).each(function() {
var opt = $('<option></option>').val(this[id_property]).html(this[label_property]);
// preserve the original jquery object on this <option> element:
opt.attr('json', JSON.stringify(this));
$(select).append(opt);
});
// bind the onchange event, and try to recreate that original jquery object
$(select).bind('change', function(event) {
// this gives me a ref to the <option> element:
var val = $(select).find(":selected");
// now how to get the original jquery object?
var item = $(val).attr('json');
});
I want that last line setting var item to the original jquery object – or somehow recreate it. I even tried doing an eval() passing in item since it is JSON formatted but it throws an error.
You can take advantage of the
data()method in jQuery, this will likely yield you the most favorable results as well as giving you the ability to avoid unnecessary custom serialization.