I'm using a Javascript bookmarklet to automatically fill out a form on a page. Some of the options given are drop down selections, which reveal different options depending on what is selected using onchange(). I have code similar to this:
/* Gets first drop down and sets value to first in list */
var dropDown1 = document.getElementById("dropDown1Name");
dropDown1.value = "option1InDropDown";
dropDown1.onchange();
/* Sets value of second drop down to option that is available when first option in first drop down is selected */
var dropDown2 = document.getElementById("dropDown2Name");
dropDown2.value = "optionRevealedByDropDown1Change";
However this doesn't work because the onchange() doesn't populate the second drop down by the time I set it to the value. By the time the script finishes executing, there is no value set in dropDown2. I've tried several methods to make the code "wait" but I haven't been able to find a correct solution. Any suggestions are appreciated.
Bind the first <select>
with the input
event which is like change
except it triggers immediately. In order to sync the first <select>
's value to the second <select>
's option and value use selectedIndex
property in the event handler.
var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');
s1.addEventListener('input', function(e) {
var idx = this.selectedIndex;
var data = idx.value;
s2.selectedIndex = idx;
}, false);
label {
margin-left: 6ex;
}
<fieldset>
<legend>Binding Input Event</legend>
<select id='s1'>
<option>---</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<select id='s2'>
<option>---</option>
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
</select>
</fieldset>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With