Reputation: 199
I have an Ajax call to an API which retrieves a list of cars and their related specifications in a subset. This displays in a div through my append. I take a value default_spec_id and try to compare with the id of each car. If it equal it sets a var defaultSet to 'checked'.
However it is not retrieving accurate results at all and the car's default spec is setting the checked status to the wrong checkbox.
My question essentially is, can I do this logic and how?
$.getJSON("{{ url('api/checkcars')}}", { option: $(this).val() },
function(data) {
if ( data.success == true ) {
$.each(data.cars, function(key, value) {
var isDefault = data.default_spec_id;
if (isDefault === value.id) {
defaultset = 'checked';
}
$('#cars').append('<div><input type="radio" value="' + value.id +'" name="spec" ' + defaultset +'> ' + value.title +'</div>');
});
}
});
JSON
{
id: 7,
name: "renault clio",
default_spec_id: 8,
cars: [
{
id: 8,
name: "Spec name 1",
description: ""
}
},
{
id: 9,
name: "Spec name 2",
description: ""
}
}
}
]
}
Upvotes: 0
Views: 444
Reputation: 6722
The problem is you are creating a variable called defaultset
with our var
keyword.
so basically it will assign that to global scope.
Your code has to look like the below
$.getJSON("{{ url('api/checkcars')}}", { option: $(this).val() },
function(data) {
if ( data.success == true ) {
$.each(data.cars, function(key, value) {
var isDefault = data.default_spec_id;
var defaultset = "";
if (isDefault === value.id) {
defaultset = 'checked';
}
$('#cars').append('<div><input type="radio" value="' + value.id +'" name="spec" ' + defaultset +'> ' + value.title +'</div>');
});
}
});
Upvotes: 1