I am just starting html/javascript, and attempting to create a simple form that populates a specific "Customer Code" when a "Customer Name" is selected from an input list (behaving like an excel vlookup). The examples I found on stackoverflow all resulted in alert windows, but I would like the value to populate in the form.
Here's my html snippet for the Customer Name dropdown list:
<select id="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>
Here's the customername to customercode mapping: Doe Inc = 276. Smith LLC = 852. Rogers and Co = 552.
I would like the customercode to update to the respective customername whenever the customername is updated (without the need for a button), as this is part of a larger form that will an Submit button (in other words, I don't want users to have to click "Submit" to retrieve the customercode, then "Submit" again later in the form).
Thanks!
In order to be included in a form submission, your form controls need to successful controls, which at the simplest means they need a name=""
value:
<select id="customername" name="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>
</select>
If what you actually care about submitting is the customercode, and the customername is just the "friendly" version, add the value
attribute to your options, and rename the select appropriately:
<select id="customercode" name="customercode">
<option value="">Select one...</option>
<option value="276">Doe Inc</option>
<option value="852">Smith LLC </option>
<option value="552">Rogers and Co </option>
</select>
If you want both "values" to be visible on the form and included in the form submission, you could use a data-
attribute to sync a readonly input:
<select id="customername" name="customername">
<option data-value="">Select one...</option>
<option data-value="276">Doe Inc</option>
<option data-value="852">Smith LLC </option>
<option data-value="552">Rogers and Co </option>
</select>
<input type="text" name="customercode" id="customercode" readonly />
Then use some JavaScript to sync them:
var select = document.getElementById('customername');
select.onchange = function(e) {
var value = select.options[select.selectedIndex].dataset.value;
var input = document.getElementById('customercode');
input.value = value;
}
Example jsFiddle: https://jsfiddle.net/27jx0q3a/3/
Some links, to help: