Script to Calculate By Dropdown without onclick

Asked

Viewed 269 times

2

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

Another thing I wanted is when I marked the checkbox 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>

1 answer

2


You can wait for the event of keyup 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 wait for the event change in the select and in the checkbox. Thus, the result will be modified whenever a different number is chosen in the select and/or the checkbox is marked/unchecked. 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>

  • And how to pass this result to a variable or field in php?

  • @Fabiohenrique in this case it is more interesting you open a new question, are different doubts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.