How to know if the person is legal?

Asked

Viewed 4,589 times

-2

I need help creating a Javascript code or using jQuery, which should read the value of the person’s date of birth (I’m using datepicker) and calculate how old they are. I have to show in div speaking if she is major or not, I have following code:

$("#entraridade").click(function () {
    var idade = 2016 - $("#date").val();
    $("#mostrar").text("Ola " + $("#name").val());
    $("#mostrar2").text("sua idade e :" + $("#idade").val());
});
$("#datepicker").datepicker({
    showOtherMonths: true,
    selectOtherMonths: true,
    dateFormat: 'dd-mm-yy',
    dayNames: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
    dayNamesMin: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S', 'D'],
    dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'],
    monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
    monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
    nextText: 'Proximo',
    prevText: 'Anterior'
});
<body>
  <form id="form">
    Nome:
    <input type="text" id="name"><br>
    Data de nascimento:         
    <input type="text" id="datepicker" name="data"/><br>
    <input type="button" id="entraridade" value="Ok">            
  </form>
  <div id="resultado"></div>
  <div id="resultado2"></div>
</body>

  • first vc defines what is the age of majority (in case 18 years), then it is only subtract year (current - ano_birth) if the result is less than the age of majority (18), it is smaller, if not greater.

1 answer

4

I used a function that returns the difference between the current year minus the proposed one which will return to age.

See working:

function getIdade(data) {
   var hoje = new Date();
  
    var nascimento = new Date(convertDateMMDDYYY(data.split("/")));

    //Retorna a diferença entre hoje e a data de nascimento em anos.
    var ano = hoje.getFullYear() - nascimento.getFullYear();
 
    //Retorna a diferença de mês do mês de nascimento para o atual.
    var m = hoje.getMonth() - nascimento.getMonth();

    //Caso ainda não tenha ultrapassado o dia e o mês
    if (m < 0 || (m === 0 && hoje.getDate() < nascimento.getDate())) {
        ano--;
    }
    return ano;
}

function convertDateMMDDYYY(datearray) {
  return datearray[1] + '-' + datearray[0] + '-' + datearray[2];
}

function Is18() 
{
  var data = document.getElementById("datepicker");
   
  if(getIdade(data.value) >= 18)
       document.getElementById("resultado").innerHTML= "Você tem 18 ou mais anos de idade!";
  else
     document.getElementById("resultado").innerHTML="Você não tem 18 anos!";
}

$('#datepicker').datepicker();

   $.datepicker.regional['pt-BR'] = {
                closeText: 'Fechar',
                prevText: '&#x3c;Anterior',
                nextText: 'Pr&oacute;ximo&#x3e;',
                currentText: 'Hoje',
                monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho',
                'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
                monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
                'Jul','Ago','Set','Out','Nov','Dez'],
                dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
                dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
                dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
                weekHeader: 'Sm',
                dateFormat: 'dd/mm/yy',
                firstDay: 0,
                isRTL: false,
                showMonthAfterYear: false,
                yearSuffix: ''};
        $.datepicker.setDefaults($.datepicker.regional['pt-BR']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
 <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

Nome:
    <input type="text" id="name"><br>
    
<p>Data de nascimento: <input type="text" id="datepicker"></p>
    <input type="button" id="entraridade" onclick='Is18()' value="Ok">
    <div id="resultado"></div>

  • In the part of : var data = Document.getElementById("datepicker"); You used pure Javascript?

  • @user49003 yes, only the part of the datapicker I used Jquery.

  • Helped me a lot, obg.

  • Just a little doubt, is there any way I can do it only in jQuery? I’m a little experienced with jQuery I’m starting now.

  • Ha ta good, what is the error in this part? because I tried and it didn’t work, look: var data = $("datepicker"). val(); if ($("datepicker"). val() >= 18) Alert("You are 18 or older!" ); Else Alert("You are not 18 years old!");

  • It has to be the same comment.

  • Ha yes, thank you very much helped!

  • Marconi, I don’t know if it’s the snippet, but here it only considers 18 years if the date is less than June 1, 1998. Any date greater than this to date(29) is considered to be less than 18.

  • @diegofm I saw here, rs it seems that this date that you passed the new date(data) is failing to format back. How strange this. ushaushausa

  • @diegofm thanks for the tip, really was wrong, corrected :);

  • @user49003 Just a recommendation regarding your request to do only with jQuery, always prefer pure Javascript (Vanilla) to jQuery, which is nothing more than a Javascript library, as it will always be faster, use jQuery only in essential cases and when you need itmaintain compatibility with older browsers, unlike jQuery haters, I’m not saying don’t use, but use when needed. :)

  • ha ta good thanks for the tip.

  • Just one detail I needed that code only in jQuery. :(

Show 8 more comments

Browser other questions tagged

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