Sine Burridge Sine Burridge - 1 month ago 6
jQuery Question

Display calculation without button click

I'm looking to output a calculation (the difference between two time inputs) without having to click a button for a result. I have it working with a button but is there any way it can be displayed 'live' or instantly?

HTML:

<input type="time" id="time1">
<br>
<input type="time" id="time2">
<br>
<button>CLICK</button>
<br>
<label>Difference:</label>
<input type="time" id="difference" disabled>


jQuery:

$('button').on('click', function() {
var time1 = $('#time1').val(),
time2 = $('#time2').val(),
hours = time2.split(':')[0] - time1.split(':')[0],
minutes = time2.split(':')[1] - time1.split(':')[1];

minutes = minutes.toString().length < 2 ? '0' + minutes : minutes;
if (minutes < 0) {
hours--;
minutes = 60 + minutes;
}
hours = hours.toString().length < 2 ? '0' + hours : hours;
$('#difference').val(hours + ':' + minutes);
});


JSFiddle

Thanks

Leo Leo
Answer

I think the function you are looking is change() from JQuery, which listens for the element within the selector:

https://api.jquery.com/change/

Here is what your selectors and code should look like in the JS:

$('#time1,#time2').change( function() {
  console.log('this is to test in console how it changes');
  var time1 = $('#time1').val(),
    time2 = $('#time2').val(),
    hours = time2.split(':')[0] - time1.split(':')[0],
    minutes = time2.split(':')[1] - time1.split(':')[1];

  minutes = minutes.toString().length < 2 ? '0' + minutes : minutes;
  if (minutes < 0) {
    hours--;
    minutes = 60 + minutes;
  }
  hours = hours.toString().length < 2 ? '0' + hours : hours;
  $('#difference').val(hours + ':' + minutes);
});

HTML (without button):

    <input type="time" id="time1">
    <br>
    <input type="time" id="time2">
    <br>        
    <label>Difference:</label>
    <input type="time" id="difference" disabled>

One thing to take in consideration is that the change waits for the whole input to be for example 4:08 p.m. If you change only the hour, it won't work, you have to put all the time for both and then it will throw you the answer in the other input box. Which makes sense because until the whole date / time is entered it shouldn't be doing any calculations.

Hope this helps !

Leo.

Comments