Check user Age using Jquery(datepicker) & JSP

Asked

Viewed 288 times

0

Needing to implement a javascript function where calculates user age, informs an alert if it is under 18.Use Jquery library along with JSP,where datepicker is automatically loaded given a framework Annotation.

Excerpt from the Code 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");
}  
  • What you can start to see is that you have not closed the datepicker function. There is a line missing with });

  • Another thing is that you have to have referenced the jquery and used that code snippet within a $(Document) function. ready(Function(){ //here });

  • Finally check for javascript error in the browser console (F12).

1 answer

1

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

As a matter of typing I suggest using Number to do the math 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>
<script src="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" />

  • Error when trying to identify the element Error "Typeerror: $(...). datepicker is not a Function[Learn More]",will be due this searching for the name.

  • @Rafaelluz in this case I think you are forgetting to join the jQuery library or jQuery UI. Join the script that I have in response.

  • I added jquery-ui.js but it interfered with my layout project, even though it didn’t work,as I am using Framework that loads Jquery and Bootstrap,).

  • @Rafaelluz creates a jsFiddle with the libraries you are using and with the code I indicated to understand the problem you are having, and puts here the link.

Browser other questions tagged

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