JSFiddle - React, Tailwind, and code Playground
by wirey00
HTML
<select id="job"></select>
<select id="name"></select>
JavaScript
var data = {
"Company": [
{
"Position": "Manager",
"Name": {
"11": "joe",
"12": "bill",
"166": "John"
}},
{
"Position": "Tech",
"Name": {
"11": "Bob",
"12": "Cindy",
"166": "Karl"
}},
{
"Position": "Sales",
"Name": {
"11": "Sam",
"12": "Ron",
"166": "Sara"
}}
]
};
$.each(data.Company, function(i, v) {
// create option with value as index - makes it easier to access on change
var options = $('<option/>', {
value: v.Position,
text: v.Position
}).attr('data-id',i);
// append the options to job selectbox
$('#job').append(options);
});
// bind change event
$('#job').change(function() {
// cache this
var $el = $(this);
// get data-id attr from selected option
var id = $('option:selected',this).data('id');
// empty select
$('#name').empty();
// get name values for selected option
$.each(data.Company[id].Name, function(i, v) {
// create option elements
var options = $('<option/>', {
value: v,
text: v
});
// append the options to name selectbox
$('#name').append(options);
});
}).change();// trigger change() on page load to fill name selectbox