Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Changing Values in a Form With a Drop Down Selection Box
05-13-2009, 06:12 PM
Post: #1
Changing Values in a Form With a Drop Down Selection Box
Say you have a web form and want to give your user a drop-down list of suggested entries for the form, here is a way to do it:

First create the drop-down selection box in HTML:
Code:
<form>
<select name="item" onchange="update_form(this.value);">
<option value="">Select an item</option>
<option value="1,Coat,$20">Coat</option>
<option value="2,Bag,$12">Bag</option>
<option value="3,Watch,$3">Watch</option>
</select>
</form>
I also included an onchange event in Javascript to trigger a Javascript function that will update our input form when a selection is made from one of the 3 items in the drop-down list.

The first item in the list is a dummy placeholder to display "Select an item" in the selection box before it is used.

Next we need some HTML code for our order form:
Code:
<form action="checkout.php" name="orderForm">
<table>
<tr><td>Stock #:</td><td><input type="text" name="id" value="" /></td></tr>
<tr><td>Item:</td><td><input type="text" name="item" value="" /></td></tr>
<tr><td>Price:</td><td><input type="text" name="price" value="" /></td></tr>
</table>
<input type="submit" value="Buy Now!" />
</form>

Now we add a section of Javascript code to update the form when an item is selected:
Code:
<script type="text/javascript">
<!--
function update_form(v) {
    var x = v.split(',');
    document.orderForm.id.value = x[0];
    document.orderForm.item.value = x[1];
    document.orderForm.price.value = x[2];
}
//-->
</script>

This contains a function I called update_form that takes an input parameter which is a comma-separated list of the item id, item name and item price. The lists of parameters for each item is stored as the values in the selection box list.

The list is split up into an array of the 3 parameters needed to insert into the values of the form elements. The form elements are referenced by their name in relation to their arrangement in the document hierarchy.

So hopefully this gets you started with dynamically updating form elements using Javascript.

Internet Marketing Software
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump: