...

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



mat106
06-15-2004, 03:14 PM
Hi.

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:

<html>
<head>
<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}
}
</script>
</head>

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

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?

Thanks.

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

document.form1.unit1.selectedIndex = 0

and

document.form1.unit1.selectedIndex = 1

it should be

document.form1.unit1.selectedIndex == 0

and

document.form1.unit1.selectedIndex == 1

Note the 2 equal signs

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

document.form1

but just

form

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.

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum