Reputation: 21
i'm going through a json javascript object to create the options for a select. it works ok if i use 1 element, like so (this is in my 'success' from the ajax call.... getting the data from php)...
var my_json = JSON.parse(data);
for (var a=0; a < my_json.length; a++)
{
$('#my_list')
.append($('<option', { value: my_json[a].SOMEFIELD } )
.text(my_json[a].SOMEOTHERFIELD));
}
That works fine, but instead of setting the value to just 1 field, i want to set:
value: my_json[a]
and pass 6 or 7 fields as the option value... - problem is, in my onclick function for the select, i can get the val from the select and see it's an object, but trying to get any field out of it seems to be undefined....
passed_data = $('#my_list').val();
var passed_id = passed_data[0].ID;
and tried...
var passed_id - passed_data[ID];
etc... they're undefined....
i can see "passed_data" is an object, but can't seem to get any fields out of it...
Upvotes: 0
Views: 1425
Reputation: 21
thanks guys. i ended up setting the value of the option to a
(my counter variable in the for loop). then i made the var my_json
global. that way, in my onchange function for the select, i just do:
var passed_element_number = ($'#my_select_list').val();
var passed_id = my_json[passed_element_number].ID;
var passed_otherfield = my_json[passed_element_number].OTHERFIELD;
i'm not sure why it wasn't letting me set the who json object as the value for the select option and then get the fields out 1 by 1 (probably my error, or maybe it's not possible), but this works ok....
Upvotes: 1
Reputation: 17370
If I got what you are trying to say, you need one select to have multiple values in the value? If this is the case I would suggest to add custom attributes to each of your select items, and then just read them. Something like the following:
$("#SelectBox").append($("<option />").val("OriginalValue").text("RandomText").attr("CustomAttribute","CustomAttributesValue"));
To retrieve the custom attributes you can do it like this:
$("#SelectBox").change(function() {
alert($(this).find("option:selected").attr("CustomAttribute"));
});
This will return the CustomAttribute for each Select Item.
Hopefully this helps and it is what you are asking. If not, could you clarify the question?
Thanks
EDIT: Doing this may break the page's DOCTYPE which means the page's XML is not correct. You could ammend it and add your custom attributes. Your page will render all the time (don't take me wrong) but it is not valid. Check this out if you care about the XML being correct
Upvotes: 1
Reputation: 2618
It's pretty mmuch unreadable, please edit and click on the "code" button.
Anyway, from what i've read, i dont know if it will solve your problem, but using $.each
is better i believe :
var my_json = JSON.parse(data);
$.each(my_json, function(){
$('#my_list').append($(this).SOMETHING);
});
Upvotes: 0