I've searched online and this website alike for a simple and adaptable solution but alas, no joy.
The desired process:
- The user selects an
<option>
from a<select>
list. e.g. a name. - The value of a read-only text box automatically populates based on the selected
<option>
. e.g. a phone number corresponding to the name. - Finally, both the
<select>
box and text box must each have their own values. i.e. a name and a phone number respectively.
The basic mark up:
When this changes, update the value of my text box:
<select id="name" name="name">
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>
Value contingent on the value of above box:
<input type="text" id="phonenumber" name="phonenumber" value="">
My question:
How do I achieve this using jQuery or regular Javascript? Please answer this from the perspective of a client side novice.
The solution (thanks to corroded):
I added the following to the head of my document:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#name").live("change", function() {
$("#phonenumber").val($(this).find("option:selected").attr("data-phonenumber"));
})
});
</script>
...and the following to the body of my document:
<select id="name" name="name">
<option value="" selected="selected">Please select...</option>
<option value="Elvis" data-phonenumber="11111">Elvis</option>
<option value="Frank" data-phonenumber="22222">Frank</option>
<option value="Jim" data-phonenumber="33333">Jim</option>
</select>
<input type="text" id="phonenumber" name="phonenumber" value="" readonly="readonly">
For more information on the use of data-somename as an attribute, as suggested by corroded, refer to the following links: