mercredi 9 août 2017

Adding values from checkbox and dropdown select option

I would like to add the values from checkboxes and a dropdown menu using JavaScript (no JQuery).

My first question is how best to do this... my code is bellow.

Second question is are there disadvantages to using anonymous functions to do this?

Thank you!

http://ift.tt/2wJiuJJ

HTML

<label class="checkbox" for="Checkbox1">
        <input value="50" type="checkbox" class="sum" > box 1
 </label>
 <label class="checkbox">
        <input value="50"  type="checkbox" class="sum" > box 2
  </label>
  <label class="checkbox">
        <input value="50"  type="checkbox" class="sum" > box 3
  </label>

    <br/><br/>

    <select id="select" name ="select">
        <option class="sum"></option>
        <option value="1" class="sum">option 1</option>
        <option value="2" class="sum">option 2</option>
        <option value="5" class="sum">option 3</option>
    </select>
    <br/><br/>

    Total: $<span id="payment-total">0</span>

JavaScript

/*To get checkbox values*/

var inputs = document.getElementsByClassName('sum'),
total  = document.getElementById('payment-total');

 for (var i=0; i < inputs.length; i++) {
    inputs[i].onchange = function() {
        var checkAdd = this.value * (this.checked ? 1 : -1);
        total.innerHTML = parseFloat(total.innerHTML) + checkAdd;
    }
 }

/*To get select values*/
var dropdown= document.getElementById("select");

for(j=0; j<dropdown.options.length;j++){

    dropdown[j].onchange = function() {
       if (dropdown[i].options.checked){
       var selectAdd = dropdown.options[dropdown.selectedIndex].value;
      total.innerHTML = parseFloat(total.innerHTML) + selectAdd;
      } 
   }
 }




Aucun commentaire:

Enregistrer un commentaire