Receive real-time input value

Asked

Viewed 8,659 times

1

Well, my question is this, I have a form with 2 inputs, that is for people to put 2 dates in each. If following I have a javascript that calculates the difference between the 2 dates.

I would like to know how I would do, so that without the person giving Submit on the form, as soon as the form had been completed, Alert saying that the difference of their dates was 'x'.

In other words, in real time, without having to click Submit, that javascript gave me the value of the difference variable with a Alert.

  • This is relatively simple... when should Alert? appear when you focus on input? or when you click on Ubmit before submitting the form? and what values do you want in response? days, hours?

  • 2

    The title should be more enlightening, in my opinion

  • Sergio, I wish that when I focusout, there would be an Alert of my variable difference.

  • In which format the dates are inserted?

4 answers

2

The input has an event called onkeyup, which is when the user "drops" the key. Then you check if it has already finished typing. For example, if the date is in the "dd/mm/yyyy" format, check if the value of the input x is already 10.

Using jquery:

$("#target").keyup(function() {
    var valor = $(this).val().length;
    if (valor === 10){
    // ...
    }
});

1

Talks brother,

I think jQuery would help you a lot in this case:

If you want Ubmit to be activated when Focus exits your field:

$("#seuCampo").blur(function(){
    alert(Sua função com o retorno do valor);
});

Now if you want when you finish writing the date the function is called, imagine that your date follows the default mm/dd/yyyy try this:

$('#seuCampo').change(function(){
   if($('#seuCampo').val().length === 10){
      alert(Sua função com o retorno do valor);
   }
});

You may need to validate to see if the two fields have been filled in.

I hope I’ve helped.

Hugs

  • Buddy, that’s not really what I want, I don’t want to give Ubmit, I want that when I take the mouse from the top it shows the difference without giving the Ubmit etende?

1

Basing myself in that reply from @Bacco, you can use the attribute onchange field to make this check.

function funcao(data){
  var dtInicio = document.getElementById('data1');
  var dtFim = document.getElementById('data2');

  if(dtInicio.value.length > 0 && dtFim.value.length > 0){

    dtInicio = dtInicio.value.split("/");
    dtFim = dtFim.value.split("/")
    data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
    data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);

    var total = dateDiferencaEmDias(data1, data2);
    
    if(isNaN(total)){
      alert("Data inserida invalida!");
    }else{
      alert("total de: " + total + " dias");
    }
  }
}

function dateDiferencaEmDias(a, b) {
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    
  return Math.floor((utc2 - utc1) / ( 1000 * 60 * 60 * 24) );
}
Digite uma data de inicio: <input type='text' id='data1' onchange='funcao(this.value)'><br/>
Digite outra data final: <input type='text' id='data2' onchange='funcao(this.value)'>

Obs: I’m not a fan of the use of Jquery when there is no need for it...

Update Answering Question Author’s Question

You can use the date field without any problem, and just change the type='text' for type='date'.

No matter where you call the code JavaScript, always remembering that you must respect the writing patterns HTML.

An example of the full code for you to get an idea of how you can assemble:

<html>
  <head>
    <script>
      function funcao(data){
        var dtInicio = document.getElementById('data1');
        var dtFim = document.getElementById('data2');

        if(dtInicio.value.length > 0 && dtFim.value.length > 0){

          dtInicio = dtInicio.value.split("/");
          dtFim = dtFim.value.split("/")
          data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
          data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);

          var total = dateDiferencaEmDias(data1, data2);

          if(isNaN(total)){
            alert("Data inserida invalida!");
          }else{
            alert("total de: " + total + " dias");
          }
        }
      }

      function dateDiferencaEmDias(a, b) {
        var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
        var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

        return Math.floor((utc2 - utc1) / ( 1000 * 60 * 60 * 24) );
      }
    </script>
  </head>
  <body>
    <form>
      Digite uma data de inicio: <input type='date' id='data1' onchange='funcao(this.value)'><br/>
      Digite outra data final: <input type='date' id='data2' onchange='funcao(this.value)'>
    </form>
  </body>
</html>
  • Good evening, in case you would put the form before or after javascript code? Remembering that my inputs are not text but date!

  • @Gonçalo put together the code to give you an idea of how you can do it

0

You no longer need to be observing events, let Angular.js take care of it.

To deal with the dates, use Moment.js; you can do without, but to lose your hair so young, is not even?

See an example working: http://codepen.io/edinella/pen/GJxaVz?editors=101

Browser other questions tagged

You are not signed in. Login or sign up in order to post.