请教实现一个javascript,实现textbox计算功能
各位大侠,小弟请教一段javascript
有textbox1,textbox2,textbox3,textbox4(以下简称T)这样的四个文本框。
计算公式为T1+T2+T3=T4
当T1,T2,T3里面全部都有值的时候,就进行计算,让他们的和等于T4.
当T1,T2,T3在有值的时候,其中任何一个T的值出现变换的时候,T4的值都要重新计算(这特别重要),我不能限制T1,T2,T3得到值的顺序。
当T1,T2,T3其中任意一个没有值或者值非法(非数字)的时候,就不进行计算~
----------------------
问题1:上述代码应该怎样写
问题2:这样的操作应该写在那个事件里面来处理。
备注:小弟js菜鸟,希望各位大虾在有时间,有条件的情况下稍微讲下用的方法。
在此谢过。
[解决办法]
<html>
<script language=javascript>
function isDigit(s){
var patrn=/^[0-9]*[1-9][0-9]*$/;
if (!patrn.exec(s)) {
return false;
}else{
return true ;
}
}
function a(){
var a,b,c;
if((t1.value!= " " && t2.value!= " " && t3.value!= " ") &&
( isDigit(t1.value)&& isDigit(t2.value) && isDigit(t3.value)))
{
a = parseFloat(t1.value)
b = parseFloat(t2.value)
c = parseFloat(t3.value)
t4.value = a+b+c
}
else
t4.value = " "
}
</script>
<body>
<input name= "t1 " type= "text " onchange= "a(); "> +
<input name= "t2 " type= "text " onchange= "a(); "> +
<input name= "t3 " type= "text " onchange= "a(); "> =
<input name= "t4 " type= "text ">
</body>
</html>
[解决办法]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN ">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME= "Generator " CONTENT= "EditPlus ">
<META NAME= "Author " CONTENT= " ">
<META NAME= "Keywords " CONTENT= " ">
<META NAME= "Description " CONTENT= " ">
<SCRIPT LANGUAGE= "JavaScript ">
<!--
var t1,t2,t3,t4;
t1= " ";
t2= " ";
t3= " ";
t4= " ";
String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, " ");
}
function total()
{
if(t1!= " " && t2!= " " && t3!= " ")
{
t4=parseInt(t1)+parseInt(t2)+parseInt(t3);
}
else
{
t4= " ";
}
document.all.t4.value=t4;
}
function set(o)
{
switch(o.id)
{
case "t1 ":
t1=filter(o.value);
break;
case "t2 ":
t2=filter(o.value);
break;
case "t3 ":
t3=filter(o.value);
break;
default:
break;
}
total();
}
function filter(s)
{
if((s.trim()== " ")||(isNaN(s)))
{
return " ";
}
else
{
return s;
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
T1 <input type=text id=t1 onblur= "set(this) ">
T2 <input type=text id=t2 onblur= "set(this) ">
T3 <input type=text id=t3 onblur= "set(this) ">
<br>
<br>
T4 <input type=text id=t4>
</BODY>
</HTML>