I'm building a simple search for my application and am wondering if there is way to dynamically set the values of forms based on JSON
I send a query to the API which returns a bit of JSON along with the results which indicates what the filtered dropdown boxes should be. So for example, if I'm searching for cars and in the make, I select 'Ford' this is what a typical response would look like to indicate what the other dropdown fields should look like:
{
"make": [
"Ford"
],
"model": [
"ECOSPORT",
"Fiesta",
"Focus",
"Transit"
],
"colour": [
"Blue",
"White",
"Red",
"Black"
],
"fuel": [
"Petrol",
"Diesel"
],
"transmission": [
"Manual"
],
"bodystyle": [
"Suv",
"Hatchback",
"Bus"
],
"engine": [
998,
1498,
1242,
1499,
2198
],
"door": [
5,
3
],
"interior": [
"Part leather",
"Not set",
"Cloth"
],
"age": [
"2016",
"2017",
"2011"
]
}
The original query is also returned which looks like this, (it could have multiple if more than one option was selected for the original query, for example, make and model)
[
{
"name": "make",
"value": "Ford"
}
]
What I'm looking to do is loop through the first JSON which contains the dropdown filters and loop through each form element (by name) and update the value (Except for the one in the original query, so in this case the make)
The form elemets input names match the names returned by the query:
<select name="make">
<option value="">Make (All)</option>
</select>
</div>
<div class="col span_2_of_12">
<select name="model">
</select>
</div>
<select name="transmission"></select>
In this example, I would like the code to add options to the select for 'model' and 'transmission' whilst not updating the values for 'make' as that was in the original query
I've tried to do it as a loop but it doesn't seem to do anything
var dropdown = data.dropdown;
$.each(dropdown, function (key, value) {
var item = $("input[name=" + key + "]")
item.empty()
$.each(value, function (x, y) {
item.append(new Option(y + ' (All)', ""));
item.append("<option value=" + y + ">" + y + "</option>");
});
});