faqts : Computers : Programming : Languages : JavaScript : Forms : SELECT

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 4 people (75%) answered Yes
Recently 3 of 4 people (75%) answered Yes

Entry

I need to take the values of 2 different selects and add them together and display that on the page

Apr 8th, 2003 13:21
jsWalter, John Doe,


This is an example of 2 pick lists of numbers and a pick list of math 
operations.
Make your select, hit EQUAL and you've got your answer!
A cheap calculator!
jsWalter
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<script>
function runMath()
{
	// Get first value
	var objFirst = document.getElementById( "first"  );
	var intFirst = new Number ( getSelectText ( objFirst ) );
	// Get second value
	var objSecond = document.getElementById( "second"  );
	var intSecond = new Number ( getSelectText ( objSecond ) );
	// Get operand value
	var objOperand = document.getElementById( "operand"  );
	var strOperand = new String ( getSelectText ( objOperand ) );
	// Where to place the results!
	var objAnswer = document.getElementById( "answer" );
	// Now, do the Math!
	objAnswer.value = eval ( intFirst + strOperand + intSecond )
}
function getSelectText ( objSelect )
{
	return objSelect.options [objSelect.selectedIndex].text;
}
</script>
<style>
.demo
{
	font-family: courier;
}
</style>
<html>
<head>
	<title>Untitled</title>
</head>
<body>
<select id='first' class='demo'>
	<option>1
	<option>2
	<option>3
</select>
  
<select id='operand' class='demo'>
	<option>*
	<option>/
	<option>+
	<option>-
</select>
  
<select id='second' class='demo'>
	<option>7
	<option>8
	<option>9
</select>
  
<button  class='demo' onClick='runMath()'> = </button>
  
<input type='text' class='demo' id='answer'>
</body>
</html>
<!-- eof -->