vendredi 27 janvier 2017

How to check multiple checkboxes in Javascript

I've just started to learn JavaScript and have run into a issue trying to get multiple checkboxes to work.

I am trying to calculate the cost of a product based on the options checked. However, my script is automatically assuming that all the boxes have been checked.

What is wrong with this code? Sorry if its a basic question but I have been banging my head for hours now.

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>




Aucun commentaire:

Enregistrer un commentaire