JSFiddle - React, Tailwind, and code Playground
HTML
<div id="menu">
<input type="button" onclick="runTest()" value="Run Test" />
<input type="button" onclick="reset()" value="Reset Test" />
</div>
<div>foo:</div>
<input type="text" name="foo-input" />
<input type="hidden" name="foo-hidden" />
<input type="submit" name="foo-submit" value="submit" />
<input type="button" name="foo-button" value="+" />
<div>bar:</div>
<input type="text" name="bar-input" />
<input type="hidden" name="bar-hidden" />
<input type="submit" name="bar-submit" value="submit" />
<input type="button" name="bar-button" value="+" />
<select onchange="popList(this,'foo-select');">
<option></option>
<option value="1">Foo A</option>
<option value="2">Foo B</option>
<option value="3">Foo C</option>
</select>
<select id="foo-select">
<option value=""></option>
</select>
<select onchange="popList(this,'bar-select');">
<option></option>
<option value="1">Bar A</option>
<option value="2">Bar B</option>
<option value="3">Bar C</option>
</select>
<select id="bar-select">
<option value=""></option>
</select>
CSS
input, select {
display:block;
min-width:5em;
}
select {
min-width:11em;
}
#menu {
background:#eee;
border-bottom:1px solid black;
margin-bottom:2em;
padding:1em 1em .5em;
}
#menu input {
display:inline-block;
}
JavaScript
// parent should be an object; child should be an id string or the select object
function popList(parent, child) {
var idx = parent.selectedIndex;
var txt_parent = parent[idx].text;
child = (typeof child === "string") ? document.getElementById(child) : child;
child = (typeof child === "object") ? child : null;
// some manual construction for demo
var ajaxResult = txt_parent + ' - option A\n' + txt_parent + ' - option B\n' + txt_parent + ' - option C';
jQuery.ajax({
url: "/",
success: function () {
fillList(ajaxResult, child);
}
});
}
function fillList(str, obj) {
obj.length = 0; // remove all options
var options = str.split('\n');
obj.length = options.length + 1; // (1 blank as default)
for (var i = 0, n = options.length; i < n; i++) {
obj[i + 1].value = options[i];
obj[i + 1].text = options[i];
}
}
function reset() {
$(':input:not([type="hidden"],[type="button"],[type="submit"])').val('');
$('#foo-select,#bar-select').each(function () {
$(this).get(0).length = 0;
});
}
function runTest() {
// non-select inputs : this sets all the value for inputs to their name
$(':input:not([type="hidden"],[type="button"],[type="submit"])').each(function () {
$(this).val($(this).attr('name'))
});
// select inputs : this sets the value to the 2nd list option and then calls the change event
var count = 0,
cutoff = 7500;
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
handleSelect(mutation.target);
});
});
$('select').each(function () {
observer.observe(this, { childList : true });
handleSelect(this);
});
...