簡體   English   中英

如何檢查Javascript中的多個復選框

[英]How to check multiple checkboxes in Javascript

我剛剛開始學習JavaScript,並遇到了嘗試使多個復選框正常工作的問題。

我正在嘗試根據檢查的選項來計算產品的成本。 但是,我的腳本會自動假定所有復選框均已選中。

此代碼有什么問題? 抱歉,這是一個基本問題,但是我已經幾個小時不停地動腦子了。

function cal() {

    var selectionOne = 0;
    var selectionTwo = 0;
    var selectionThree = 0;
    var total = 0;


    if (document.getElementById("1").checked = true ){
        selectionOne = 25;
    }

    if (document.getElementById("2").checked = true ){
        selectionTwo = 50;
    }

    if (document.getElementById("3").checked = true ){
        selectionThree = 100;
    }

    total = selectionOne + selectionTwo + selectionThree;

    alert ("Your total is £" + total);

}

的HTML

<html>
  <head>
    <title>Basic Pricing Script</title>
  </head>
  <body>
    <script src="script.js"></script>

    <p>Please select which options you want from the list</p>

    <form name="priceoptions">

      <input type="checkbox" id="1" name="big" value="big"> Big Prints<br>
      <input type="checkbox" id="2" name="medium" value="medium" > Medium Prints<br>
      <input type="checkbox" id="3" name="small" value="small"  > Small Prints<br>
      <input type="submit" id="button" value="Submit" onclick="cal()">

    </form>

  </body>
</html>

您的比較不正確。 單個“ =”不是比較值的正確方法,“ true”和“ ===”需要完全匹配。 更改為

if (document.getElementById("1").checked == true ){
    selectionOne = 25;    
}

=是賦值運算符。 為了進行比較,您需要使用=====

  • == :按類型比較
  • ===這按類型和值進行比較

同樣,說.checked == true是多余的。 您可以只使用.checked 此外,沒有理由聲明變量,然后在單獨的行上設置它們的值。 您可以通過使用三元運算符來減少代碼。

查看此代碼段。

 function cal() { var s1 = document.getElementById("1").checked ? 25 : 0; var s2 = document.getElementById("2").checked ? 50 : 0; var s3 = document.getElementById("3").checked ? 100 : 0; var total = s1 + s2 + s3; alert ("Your total is £" + total); } 
 <p>Please select which options you want from the list</p> <form name="priceoptions"> <input type="checkbox" id="1" name="big" value="big"> Big Prints<br> <input type="checkbox" id="2" name="medium" value="medium" > Medium Prints<br> <input type="checkbox" id="3" name="small" value="small" > Small Prints<br> <input type="submit" id="button" value="Submit" onclick="cal()"> </form> 

如果需要比較JavaScript中的兩個值,則必須使用==或===運算符:

if (document.getElementById("1").checked == true ){

如果您也可以簡化此操作:

if (document.getElementById("1").checked){

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM