通过单个javascript函数处理两个表单

时间:2013-05-18 05:08:02

标签: javascript forms

我有两个名为“sum”和“sub”的表单。如果我点击“sum”形式的提交按钮,则会调用函数Calculate,同样如果我点击“sub”形式的提交按钮,同样的函数被调用。但我希望“sum”形式的方法不应该在通过“sub”形式调用Calculate时执行。我想这可以通过if语句来完成,任何人都可以告诉我这样做的声明。

function Calculate() {
 var numsub=document.sub.subnum.value; //e.g: sub form assignment, this should not be executed on calling calculate from "sum" form

 totnumber=totnumber-parseInt(numsub);
 var sp1=document.sub.sp1.value;
 var tot1=sp1*numsub;
 totsellprice +=Math.floor(parseFloat(tot1));
 totnumsell =parseInt(numsub) + totnumsell;
 var number= document.sum.number.value;
 totnumber =parseInt(number) + totnumber;
 var sp= document.sum.sp.value;
 var total= sp*number;
 totprice +=Math.floor(parseFloat(total));
 avgbuy=totprice/totnumber;
 avgsell=totsellprice/totnumsell;
 status= "<h1>Share status</h1>Number of shares: " + totnumber + "</br>total money spent: " + totprice;
 status +="</br>Average Buying price: " + avgbuy;
  status= "</br>Number of shares sold: " + totnumsell + "</br>total money earned: " + totsellprice;
 status +="</br>Average Earning price: " + avgsell;
 document.getElementById('results2').innerHTML= status;
 }

2 个答案:

答案 0 :(得分:1)

function Calculate(type) {
 if(number=="sum")
  {
      //write the logic related to form1
      document.getElementById("sum").submit();
  }else{
      //write the logic related to form2
      document.getElementById("sub").submit();

   }

 }

答案 1 :(得分:0)

在提交时将字符串传递给javascript函数。并分别检查sub和sum表的字符串值。 Calculate('sum'); Calculate('sub')喜欢这样。