Using the id attribute of a select to process JSON data in jQuery
I am dealing with several dynamically updating select boxes, much like a auto website that dynamically updates make, model, etc. Early in my script I identify the changing select, then identify the next select and pull its id from the page like so:
var next_select_id = $(next_select).attr('id');
I call it next_select_id
because the HTML ID of any given select corresponds to the parent object type in the JSON response.
In the case of two selects with the ids "A" and开发者_开发问答 "B", upon changing A, next_select_id
should be "B". This works later in the page where I generate a URL by concatenating next_select_id
with strings (For example, it generates http://testing.com/users/B
just fine).
Later on when I attempt to process a JSON file with a parent key based on next_select_id
containing names and id values this way:
$.each(data, function(i, j){
row = "<option value=\"" + j.next_select_id.id + "\">" + j.next_select_id.name + "</option>";
$(row).appendTo(next_select);
});
The j.something.id
in this case corresponding to the ID of an ActiveRecord object.
It says "Cannot read property 'id' of undefined". Do I need to be converting next_select_id
in some way before attempting this? Thanks for your help!
It looks like you already set next_select_id to the ID string. Just remove your extra .id in that $.each and it should work. (If not, please post the code where you set next_select_id for the $.each.)
It seems I was a bit confused about the proper way to use my string assigned to a variable. In the end, the fix was a simple notational change to:
j[next_select_id]["name"]
精彩评论