Verify if user Older using Jquery (datepicker) & JSP

0

Need to implement a javascript function where it calculates the user's age, it informs an alert if it is smaller than 18. The Jquery library along with JSP, where datepicker is automatically loaded given an annotation of the Framework.

►Code Category ✓ JSP

<n:panelGridBootstrap >
  <t:property name="dtnascimento"  />
</n:panelGridBootstrap> 

✓ Javasscript

var esteAno = new Date().getFullYear();
$("input[name='dtnascimento']").datepicker({
  dateFormat: 'dd-mm-yy',
  onSelect: function(date) {
    var ano = date.split('-')[2]; // ano aqui
    var idade = esteAno - ano;

   if(idade<18){
   alert("Menor de Idade");
}  
    
asked by anonymous 13.06.2018 / 15:14

1 answer

1

Your logic is correct. I suggest you add changeYear: true, to datepicker and add } and }); that is missing in your code, to close onSelect , but also the object and method invoked in .datepicker({ .

For typing I suggest using Number to do the accounts with numbers : Number(date.split('-')[2]) .

var esteAno = new Date().getFullYear();
$("input[name='dtnascimento']").datepicker({
  dateFormat: 'dd-mm-yy',
  changeYear: true,
  onSelect: function(date) {
    var ano = Number(date.split('-')[2]);
    var idade = esteAno - ano;

    if (idade < 18) {
      alert("Menor de Idade");
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet" />

<input name="dtnascimento" />
    
13.06.2018 / 15:24