Home > Software engineering >  JavaScript Change click button for automatic
JavaScript Change click button for automatic

Time:12-26

I have this script

<script>
        function calculaDiferenca(data_inicio, data_fim) {
          var date1 = new Date(data_inicio);
          var date2 = new Date(data_fim);
          var timeDiff = Math.abs(date2.getTime() - date1.getTime());
          var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
          alert(diffDays   ' dias');
      }

      (function() {
        
          var calcBtn = document.getElementById('calcular');
          
          calcBtn.addEventListener('click', function(){
            
              var data_inicio = document.getElementById('data_inicio').value;
              var data_fim = document.getElementById('data_fim').value;
              
              calculaDiferenca(data_inicio, data_fim);
          });

})();

    </script>  

Can I change instead of clicking the button to calculate being when date1 and date2 are filled do the calculation?

 var calcBtn = document.getElementById('calcular');

CodePudding user response:

You can listen for change event on the input fields and invoke the calculation function.

let first = document.getElementById('data_inicio');
let last = document.getElementById('data_fim');

first.addEventListener('change', (e) => {
  calculaDiferenca(e.target.value, last.value)
})

last.addEventListener('change', (e) => {
  calculaDiferenca(first.value, e.target.value)
})

CodePudding user response:

And here is a working snippet:

function calculaDiferenca(ev) {
  var date1 = new Date(ini.value);
  var date2 = new Date(fim.value);
  var timeDiff = Math.abs(date2.getTime() - date1.getTime());
  var diffDays = Math.ceil(timeDiff/(1000*3600*24));
  dif.textContent=diffDays ' dia' (diffDays===1?'':'s');
  }

const [ini,fim,dif] = "data_inicio,data_fim,dif".split(",").map(t=>document.getElementById(t));
[ini,fim].forEach(e=>e.addEventListener("input",calculaDiferenca));



 
<input type="date" id="data_inicio" placeholder="inicio">
<input type="date" id="data_fim" placeholder="fim"><br>
<p>Diferenca: <span id="dif"></span></p>

CodePudding user response:

The answer from @Khalil is good. I just want to add something to make the process sequential.

Make the date2 field disabled. As:

<input type="date" id="data_fim" disabled/>

Then make it dependent on date1.

let first = document.getElementById('data_inicio');
let last  = document.getElementById('data_fim');

first.addEventListener('change', (e) => {
  last.disabled = false
  calculaDiferenca(e.target.value, last.value)
})

last.addEventListener('change', (e) => {
  calculaDiferenca(first.value, e.target.value)
})
  • Related