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’

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>

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)=>{
     // do whatever you want with this value.

This should work for, good luck.

Leave a Reply