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

Update input field value by getting value of 2 other input fields in Javascript

I have 3 input fields, I want to update the value of the 3rd one dynamically by adding the value of the 1st and 2nd input field.

1 field -> value ‘5’

2 field -> value ‘3’

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

3 field which is disabled when I finish typing in the 2nd and 1st field should have value -> ‘8’

this is the one way I tried to do it in Javascript:

document.addEventListener('DOMContentLoaded', function () {
   let time_in_min = document.querySelector('#length_min').value;
   let time_in_sec = document.querySelector('#length_sec').value;

   let total_time_in_secs = (min * 60) + sec;

   document.querySelector('#total_length_sec').value = total_time_in_secs;
});

thi is the html input

<div class="in">
   <input id="total_length_sec" name="total_length_sec" type="number" min="0" disabled="disabled" class="validate" />
   <label for="total_length_sec">Total time in seconds</label>
</div>

but when I reload the page in the 3rd field the value it’s ‘0’ and it remains 0 even if I change the value of the 1st and 2nd field

>Solution :

The code that you wrote is runs in the beginning and not every time the value of the inputs fields changes, So what you have to do is to listen to "change" event on the input.

const input = document.querySelector("input");

input.addEventListener("change", (event)=>{
     console.log(event.target.value);
     // do whatever you want with this value.
});

This should work for, good luck.

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