Fill Second Input automatically when filling the First

2

I have a input that I'll give the name of input-1 , and there I'll insert this: 12:00

When I have a second input that I am going to give the name of input-2 , it is possible to insert in input-1 : 12:00

It does not input-2 can automatically fill the time I put in input-1 but with another two hours.

Example :

I put 10:00 on input-1 and no input-2 on 12:00 .

Is it possible to do this?

    
asked by anonymous 23.04.2015 / 01:10

2 answers

3

Yes,

You should add an event listener in input-1 of types

  • KeyDown (when the key is pressed but does not release) or,
  • KeyUp (when the key is released) or,
  • KeyPress (when key is pressed)
  • or Blur (when exiting the input)

And make this trigger a function that treats data from input-1 and insert them into input-2 .

Taking the following code as an example:

Javascript with JQuery to make it easier to view the binding of the event:

$(document).ready( function(){
    $('#input-1').keyup(function (e) {
        var patt = /([0-9]{1,2}:[0-9]{2})/;
        // Testando se o valor digitado já é algo como nn:nn
        if (patt.test(e.target.value)) {
            var strsplit = e.target.value.split(':');
            var hora = Number(strsplit[0]) + 2;
            var min = (strsplit[1]);
            var stringfinal = '';
            // ex. se hora = 24 então vira 00, se hora = 25 então vira 01;
            if (hora > 23) {
                hora = hora - 24;
            }
            if (hora < 10) {
                stringfinal += '0' + hora;
            } else {
                stringfinal += hora;
            }
            stringfinal += ':' + min;
            $('#input-2').val(stringfinal);
        } else {
            // Faz nada...   
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputid="input-1" type="text">
<input id="input-2" type="text">

This should give the planned effect, the function I did was pretty basic and can be greatly improved, it's more a proof of concept.

Events can be checked even without jQuery. More information can be found at MDN Input and

I hope this answers your question.

    
23.04.2015 / 02:16
4

You could create a function to get the value of the first input and set a second variable to add, in your case, the value of 2 . So it will get the value, and it will add up to the number defined in the variable.

function calc()
{
  var a = "2";
  var b = valor.value;

  total.value = parseFloat(a) + parseFloat(b) + ':00';
}
Valor: <input type="time" id="valor" onkeypress="calc()"><br/><br/>
Total: <input type="time" id="total">

In this case, I put :00 just to follow your example, but it's irrelevant if you do not have to use it.

    
23.04.2015 / 01:56