0

我需要创建一个计算器来调用不同的函数,具体取决于哪个字段中有条目。
“initial_hosts”必须有一个条目,然后用户可以在“Time”或“Num”中输入值,但不能同时输入(错误消息)。

如果单击“计算”时在“时间”中输入了一个值,我希望它调用函数 number(),如果“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>

我不知道我该怎么做,提前谢谢你:)

4

2 回答 2

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();"/>
于 2012-04-13T17:52:21.077 回答
0

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

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

并更改您的按钮以运行计算();

<input type="button" style="height: 35px; width: 100px" value="Calculate"  onclick="javascript:calculate();"/>
于 2012-04-13T17:48:26.423 回答