Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Change click button for automatic

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');

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading