根据输入的字段调用不同的功能

时间:2012-04-13 17:43:02

标签: javascript html

我需要创建一个计算器,根据哪个字段有条目调用不同的函数。
" initial_hosts"必须有一个条目,然后用户可以输入"时间"或者" Num"但不是两者(错误信息)。

如果在"时间"中输入值当"计算"单击我希望它调用函数编号()和如果" Num"调用函数timeCal()

<script language="javascript" type="text/javascript">
  function timeCal(){
    a=Number(document.calculator.initial_hosts.value);
    b=Number(document.calculator.Num.value);
    // Example of cal
    c=a*b;
    document.calculator.total.value=c;
  }
</script>

<script language="javascript" type="text/javascript">
  function number(){
    a=Number(document.calculator.initial_hosts.value);
    b=Number(document.calculator.Time.value);
    // Example of cal
    c=a*b;
    document.calculator.total.value=c;
  }
</script>

<div class="figure2"> 
  <form name ="calculator" class="form">
    <p>You can use the calculator below to see the approximate number of infected hosts after a given amount of time </p>
    <label for="Fname">initial hosts:</label><br/>
    <input type="text" name="initial_hosts"/><br/>

    <label for="Fname">Trigger Date:</label><br/>
    <input type="text"  id="TTime" value="" />
    <br/><br/>

    <font face="arial, helvetica" size="2" >Note: Enter the time space or the number of targets </font><br/>

    <label for="Time">Enter Time:</label><br/>
    <input type="text" name="Time"/><br/>

    <label for="Num">Target Number :</label><br/>
    <input type="text" name="Num"/><br/>

    <label for="total">Outcome:</label><br/>
    <input type="text" name="total"/><br />
    <br/>

    <p><input type="button" style="height: 35px; width: 100px" value="Calculate"  onclick="javascript:timeCal();"/>
  </form>
</div>

我不知道我怎么能这样做,谢谢你提前:)

2 个答案:

答案 0 :(得分:1)

<script language="javascript" type="text/javascript">  
    function callAppropriateFunction(){
        numValue=document.calculator.Num.value;
        timeValue=document.calculator.Time.value;  
        if(numValue!='')
            number();
        else if(timeValue!='')
            timeCal();
        else
            alert("please select either number or time");
    }
</script>


<input type="button" style="height: 35px; width: 100px" value="Calculate"  onclick="javascript:callAppropriateFunction();"/>

答案 1 :(得分:0)

创建一个名为calculate();的新函数,然后从那里检查哪个字段中包含数据。

function calculate() {
   if (document.calculator.time.value != ""){
       timeCal();
   }else {
       number();
   }
}

并更改按钮以运行calculate();

<input type="button" style="height: 35px; width: 100px" value="Calculate"  onclick="javascript:calculate();"/>
相关问题