Input type="date"

Asked

Viewed 1,537 times

0

I need to take the amount corresponding to the year of one <input type="date"> and subtract from the current date to display a user’s age (javascript). However, my result always gives "Nan". How do I fix it? And how do I get the JS itself to pick up the date (like, for example, the date("Y") of PHP)?

var data = parseInt($('input[id=nasc]').val());
var ano = 2017;
var idade = ano - data;
localStorage.setItem("diaNasc", idade);
  • The solution worked out?

  • Know that the input date is specific to Google Crone, other browsers may not work well with it!

1 answer

1

To work with date in and convert a date of input of type="date" use the new Date of where:

var dataAtual = new Date(); // retornar a data atual (Date)

and

var dataInput = new Date($("#nasc").val()); // converte o valor para Date

then just do the subtraction operation with the method getFullYear():

var diferenca = dataAtual.getFullYear() - dataInput.getFullYear();

Complete code:

$("#nasc").on('blur', function() {
  calcular_idade();
});

function calcular_idade() {
  if ($('#nasc').val() != '') {
    var dataInput = new Date($("#nasc").val());
    if (!isNaN(dataInput)) {
      var dataAtual = new Date();
      var diferenca = dataAtual.getFullYear() -
                      dataInput.getFullYear();
      $("#lblidade").html(diferenca);
      return true;
    }
  }
  $("#lblidade").html('Data inválida');
  return false;  
}

calcular_idade();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" name="nasc" id="nasc" value="1980-10-01" />
<label id="lblidade"></label>

References:

  • @Leocaracciolo the answer is about the two tags, didn’t I understand.? And something else has jQuery in question.

  • Okay, I hadn’t analyzed his code, $('input[id=nasc]'). val()); I only saw the question --- display a user’s age (javascript)

Browser other questions tagged

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