How to update an input value with the value from a selected option using Prototype

Published on Aug. 12, 2008, 10:32 a.m.

Today, I needed to set the value of an HTML input element based on the value of a option in a select element. This is fairly easy to do with Prototype's writeAttribute. Here's an example:

A simple javascript function to do the work:
function populate_input(){
var field = $('tf_select').getValue();
$('tf').writeAttribute('value', field);

A simple HTML snippet to see it in action:
<p><select id="tf_select" name="tf_select" onchange="populate_input();">
<option value="">- choose one -</option>
<option value="v1">value 1</option>
<option value="v2">value 2</option>
</select><br/><input type="test" id="tf" name="tf" value=""/></p>

And yes... I know the title of this post is almost longer than the post itself!
comments powered by Disqus