Reputation: 113
Im doing a little project with flask. Right now, im trying to add options to a select from a JSON object.Despite being able to insert options, i cant access their value
This my flask code:
for dealership in session.query(Dealership).filter_by(ownerID = userId).all():
dealership_list.append({'Name' : dealership.name})
return jsonify(names = dealership_list)
Ajax code:
success:function(result){
$.each(result.names, function(Name, value) {
$('#dealerships').append($("<option/>", {
value: Name,
text: value
}));
});
},
Upvotes: 0
Views: 46
Reputation: 113978
each item in result.names
is a dealership (as defined by your view function).
each dealership is a dict consisting of {"Name":the_name_of_this_dealership}
so $.each(result.names,function(data){console.log(data)}
should print each object which is {"Name":some_dealership_name}
so just change it to
success:function(result){
$.each(result.names, function(dealership) {
$('#dealerships').append($("<option/>", {
value: dealership.Name,
text: dealership.Name
}));
});
},
better yet just change your python code to just return a list of names since thats the only data you are using
dealerships = session.query(Dealership).filter_by(ownerID = userId).all()
names = [dealership.name for dealership in dealerships]
return jsonify(names = names)
and just change your js to
success:function(result){
$.each(result.names, function(index,a_dealer_name) {
$('#dealerships').append($("<option/>", {
value: a_dealer_name,
text: a_dealer_name
}));
});
}
Upvotes: 1
Reputation: 113
@JoranBeasley Awesome!I used the second solution, but added/change the following:
$.each(result.names, function(key,name) {
$('#dealerships').append($("<option/>", {
value: name,
text: name
}));
});
This because your solution was printing the index instead of value.Thanks for the help!
Upvotes: 1