2015-11-24 115 views
0

我正在計算基於userinput的價格。當用戶輸入頁數時,它將乘以2,結果將顯示在#result框中。現在,當用戶單擊複選框時,總數(#result)值將乘以3並顯示在#result文本框中。當用戶點擊它時,舊的結果應該顯示在文本框中。複選框單擊作品,取消選中複選框不工作Javascript

例,

 Total number of pages: 2 ---> total: 4 
     checkbox clicked ----> total: 12 
     checkbox unchecked ---> total: 4 

當單擊顯示值12的複選框,但是當我取消選中該複選框值仍是12,而不是顯示4 ...

誰能幫助我與解決方案

<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Calculating</title> 
    <script> 
     function calculate() 
     { 
    var myBox1 = document.getElementById('pages').value; 
      if(isNaN(myBox1)) 
      { 
       alert('Enter only numbers'); 
      } 
      else 
      { 
       const myBox2=2; 
       var result = document.getElementById('result'); 
       var myResult = myBox1 * myBox2; 
       result.value = myResult; 
      } 
     } 
     function checkbox1() 
     { 
      var result1 = document.getElementById('result').value; 
      const bresult=result1; 
      if(document.getElementById('ckbox').checked === true) 
      { 
       const checks=3; 
       var myResult1=result1 * checks; 
       result.value = myResult1; 
      } 
      if(document.getElementById('ckbox').checked === false) 
      { 
       result.value=bresult; 
      } 
     } 
    </script> 
</head> 
<body> 
     <table> 
    <tr> 
     <td>Number of Pages</td> 
     <td>Check Boxes</td> 
     <td>Total</td> 
    </tr>  

    <tr> 
     <td><input id="pages" type="text" oninput="calculate()" /></td> 
     <td><input type="checkbox" id="ckbox" onclick="checkbox1()">Assistance</td> 
     <td><input id="result" /></td> 
    </tr> 
    </table> 
    </body> 
    </html> 

回答

0

雖然取消選中該複選框,你重新設置結果值。根據頁面值計算值。

請嘗試下面的代碼。

function calculate() 
 
{ 
 
    var myBox1 = document.getElementById('pages').value; 
 
    if(isNaN(myBox1)) 
 
    { 
 
     alert('Enter only numbers'); 
 
    } 
 
    else 
 
    { 
 
     const myBox2=2; 
 
     var result = document.getElementById('result'); 
 
     var myResult = myBox1 * myBox2; 
 
     result.value = myResult; 
 
    } 
 
} 
 

 
function checkbox1() 
 
{ 
 
    var result1 = document.getElementById('result').value; 
 
    const bresult=result1; 
 
    if(document.getElementById('ckbox').checked === true) 
 
    { 
 
     const checks=3; 
 
     var myResult1=result1 * checks; 
 
     result.value = myResult1; 
 
    } 
 
    else 
 
    { 
 
     var myBox1 = document.getElementById('pages').value; 
 
     const myBox2=2; 
 
     result.value=myBox1 * myBox2; 
 
    } 
 
}
<table> 
 
    <tr> 
 
     <td>Number of Pages</td> 
 
     <td>Check Boxes</td> 
 
     <td>Total</td> 
 
    </tr>  
 

 
    <tr> 
 
     <td><input id="pages" type="text" oninput="calculate()" /></td> 
 
     <td><input type="checkbox" id="ckbox" onclick="checkbox1()">Assistance</td> 
 
     <td><input id="result" /></td> 
 
    </tr> 
 
</table>

希望這會幫助你。

+0

它正在工作!謝謝@balachandar – JavaLearner1