View Full Version : Passing form <option> values to javascript

06-15-2004, 04:14 PM

I'm trying to create a form for users to submit a value in a text box and choose a unit from a drop down menu. On submitting, the script will then carry out certain conversions of the inputted value based on the unit that was chosen from the drop down menu and output the converted values. This is what i've got so far:

<script type="text/javascript">
function cal(form) {if (document.form1.unit1.selectedIndex = 0){
var i = document.form1.text1.value/3
var a = document.form1.text1.value/2
document.form1.answer.value = i
document.form1.answer1.value = a}
else if (document.form1.unit1.selectedIndex = 1)
{var i = document.form1.text1.value/2
var a = document.form1.text1.value/3
document.form1.answer.value = i
document.form1.answer1.value = a}

Input a value and choose calculate:
<form name="form1">
<input type="text" name="text1">&nbsp;&nbsp;
<select name="unit1">
<option selected>Joules</option>
<input name="button" type="button" onClick="cal(this.form)" value="Calculate">
<input type="text" name="answer">
<input type="text" name="answer1">

The problem is that i can't seem to get the script to respond to the option chosen from the drop down menu. It responds it all kinds of weird (wrong) ways. If think the problem is with the bold parts of the code. Can anyone help?


Mr J
06-15-2004, 10:01 PM
Where you have

document.form1.unit1.selectedIndex = 0


document.form1.unit1.selectedIndex = 1

it should be

document.form1.unit1.selectedIndex == 0


document.form1.unit1.selectedIndex == 1

Note the 2 equal signs

06-16-2004, 07:23 AM
And you're already passing the form reference to the function.
So you don't need to do


but just


which is the variable you used for the function parameter.

And you can take out these 2 lines outside of the if-else condition as those will be executed whatever the selection is.

document.form1.answer.value = i
document.form1.answer1.value = a

Just put them after the if-else condition.

06-16-2004, 11:17 AM
Thanks. The script now works fine.