Is there any plugin, preferably vanilla but jquery plugins work too, that can turn a JavaScript object into respective select elements.
obj = {
Ford: {
1: "Focus",
2: "Fiesta"
},
Toyota: {
1: "Prius",
2: "Avensis"
}
}
AwesomePluginMagic(obj);
Which should give me
<select name="primary">
<option value="0" selected>Ford</option>
<option value="1">Toyota</option>
</select>
<select name="secondary">
<option value="1">Focus</option>
<option value="2">Fiesta</option>
<option class="hidden" value="1">Prius</option>
<option class="hidden" value="2">Avensis</option>
</select>
And should then listen for changes and visualize the appropriate options in the relevant select element.
Disclaimer: I don't want you to write a function for me, I'm asking for a plugin already made, but if you insist I'll use it. Also the input object can be of any format, I just made up one for the example.
JS is object oriented, why not use objects, something like this:
The prototype is reusable, you can create multiple "select pairs" just by creating a new object using
selectPair
prototype and passing the needed data object and the element to append theselect
elements.Added a
data-car
value to the secondary options so they have a reference to the primaryselect
. Also added achange
listener for the primary which changes the.hidden
for the secondary options based on the selected item.Disclaimer: It will work with the current format, if obj has a different format it needs to be modified. I don't think it's possible though, unless some restrictions are set for the format of the given object.
jsfiddle DEMO
An example on how to implement this without any library.