1. 程式人生 > >javascript/HTML實現多個text控制元件自動/動態計算總數

javascript/HTML實現多個text控制元件自動/動態計算總數

<html>
<head>
<title>untitled</title>
<style type="text/css">

input {width: 40px;}

</style>
<script type="text/javascript" language="javascript">

function autocalc(e)
{
var field, val,total=0,i=0;
for (i; i< arguments.length; ++i) //loop through text elements
{
field = arguments[i];
val = parseFloat(field.value); //get value
if (!isNaN(val)) //number?
{
total += val; //accumulate
}

}
e.form.total.value = total; //out
}


function EnsureDecimal(e)
{
      if (((event.keyCode < 48) || (event.keyCode > 57)) && (event.keyCode != 46))
      {                  
         event.returnValue = false;
      }
      else if((e.value.indexOf('.')!=-1) && event.keyCode==46)
      {
        event.returnValue = false;
      }
       
}


</script>
</head>
<body onload="document.forms[0].reset()">
<form>
<table cellspacing="8">
<tr>
<td>value 1:<input name="text1" type="text" OnKeyPress="EnsureDecimal(this)" onkeyup="return autocalc(this,text2,text3)" tabindex="1"></td>
<td rowspan="3"><strong>total:</strong><input name="total" type="text" readonly="readonly" value="0" tabindex="-1"></td>
</tr><tr>
<td>value 2:<input name="text2" type="text" OnKeyPress="EnsureDecimal(this)" onkeyup="return autocalc(this,text1,text3)" tabindex="2"></td>
</tr><tr>
<td>value 3:<input name="text3" type="text" OnKeyPress="EnsureDecimal(this)" onkeyup="return autocalc(this,text1,text2)" tabindex="3"></td>
</tr>
</table>
</form>
</body>
</html>