Calculate Dropdown Script without onclick

2

I need in below, when selecting dropdown it does the calculation automatically without having to click the calcular button.

Another thing I wanted is: when I checked the checkbox it multiplied by 2 the total value.

<head>
    <script type="text/javascript">
        window.onload = function () {
            var i = function (id) {
                return document.getElementById(id);
            }

            i("calcula").onclick = function () {
                var c1 = i("campo1").value;
                var c2 = i("children-qnt").value;
                var c3 = i("iv").value;
                i("resultado").innerHTML = parseInt(c1) * parseInt(c2) * parseInt(c3);
            }
        }
    </script>
</head>
<body>
    <input type="checkbox" id="iv" value="2"/></br>
    <input type="text" id="campo1" value="10"></br>
    <select name="children-qnt" id="children-qnt">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    <div id="children">
        <button id="calcula">calcular</button>
        Result: <span id="resultado">0</span>
    </div>
</body>
    
asked by anonymous 28.02.2015 / 23:03

1 answer

2

You can wait for the keyup event in your field to update the result. This event will be triggered when the key is pressed and released.

To make it more automatic, you can expect the event change in select and checkbox . Thus, the result will be modified whenever a different number is chosen in select and / or checkbox is selected / deselected. Here is an example:

var $campo = byId('campo'),
    $select= byId('children-qnt'),
    $checkbox = byId('iv');

function byId(element){
  return document.getElementById(element);
}
    
function updateResult(){
  var result =  parseInt($campo.value) *
                parseInt($select.value);
  byId('resultado').innerHTML = $checkbox.checked ? result * 2 : result;
        
  /* 
   *  Isso seria o mesmo que:
   *
   *  if($checkbox.checked) {
   *       byId('resultado').innerHTML = result * 2;
   *  } else {
   *       byId('resultado').innerHTML = result;
   *  }
   */     
}
  
$campo.addEventListener('keyup', updateResult);
$select.addEventListener('change', updateResult);
$checkbox.addEventListener('change', updateResult);
<input type="checkbox" id="iv"/></br>
<input type="text" id="campo" value="10"></br>
<select name="children-qnt" id="children-qnt">
   <option value="0">0</option>
   <option selected value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>
<div id="children">
  Result: <span id="resultado">10</span>
</div>
    
01.03.2015 / 00:57