Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reusable Functions

Status
Not open for further replies.

TheMuffin

Technical User
Mar 18, 2007
3
PE
Hi! How can a function be written so that it is reusable within the same form? eg, if I wish to place another select menu and result in the following code (eg.mySelect2, mySpan2) so that whichever select menu is chosen displays its own result:

Code:
<html>
<head>
<script type="text/javascript">

function updateForm(doit)
{
selected = doit.mySelect.selectedIndex;
values = doit.mySelect.options[selected].value;

document.getElementById("mySpan").innerText = values;
}

</script>
</head>
<body>
<form name="myForm" id="myForm">
<p>
<tr><td name="48">	
<select name="mySelect" id="mySelect" onChange="updateForm(this.form)">
<option value="1.99">1
<option value="3.59">2
<option value="5.29">3
<option value="6.99">4
</select>
$<span name="mySpan" id="mySpan">1.99</span
</td></tr>	
</form>
</body>
</html>

Thanks!

TheMuffin
 
Found the solution thanks to rwedge at codingforums.com:

Code:
<html>
<head>
<script type="text/javascript">

function updateForm(doit,total)
{
document.getElementById(total).innerText = doit.value;
}

</script>
</head>
<body>
<table>
<form name="myForm" id="myForm">
<tr><td name="48">     
<select name="mySelect" id="mySelect" onChange="updateForm(this,'mySpan')">
<option value="1.99">1
<option value="3.59">2
<option value="5.29">3
<option value="6.99">4
</select>
$<span name="mySpan" id="mySpan">1.99</span>
</td></tr>     
</form>

<form name="myForm1" id="myForm1">
<tr><td name="48">     
<select name="mySelect1" id="mySelect1" onChange="updateForm(this,'mySpan1')">
<option value="1.99">1
<option value="3.59">2
<option value="5.29">3
<option value="6.99">4
</select>
$<span name="mySpan1" id="mySpan1">1.99</span>
</td></tr>     
</form>
</table>

</body>
</html>

His explanation:
Quote:
You could pass the target span as an argument and you can pass the select value

Hope somebody else also finds it useful!

TheMuffin
 
Ultimater at webdeveloper.com showed this to be better for x-browser compatibility:

Code:
function updateForm(doit,total)
{
document.getElementById(total).firstChild.data = doit.value;
}

TheMuffin!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top