I am trying to create a Javascript function that will take the value from one select field and then use that to compare a JSON array . If any array elements match the user selected value then the function will add those values to another select field.
Logic:
Code:
//this function modifies a select field depending on what value was selected by its predecessor
function tariffs()
{
//variable selection equals the selected value chosen by the user in that field
var selection = document.getElementById('tariff_net').options[document.getElementById('tariff_net').selectedIndex].value
//for loop to go through JSON values to compare with the value chosen by the user
for(var i = 0; i < values.preset_name.length ; i++)
{
//if the JSON value equals the user selected value
if (values.preset_name[i] == selection)
{
//append it to the "tariff_name" select field
var option = values.preset_name[i];
var selectfield = document.getElementById('tariff_name');
selectfield.appendChild(option);
}
}
}
Here is a screenshot showing the two select fields (the one on top will affect the bottom select fields options)
https://i.sstatic.net/RNI63.png
At the moment my code is not working and I am getting a Javascript Error:
Could not convert JavaScript argument arg 0 [nsIDOMHTMLInputElement.appendChild] [Break On This Error] selectfield.appendChild(option);
I am also wondering how I would be able to make the Javscript refresh the select field of all values and then repopulate it. This would prevent a large accumulation of duplicated options whenever the function is called.
Thanks
appendChild
takes an element, not a string. Select options have a constructor to help you:
var option = new Option(values.preset_name[i]); //Dom element instead of a string
var selectfield = document.getElementById('tariff_name');
selectfield.appendChild(option);