How to Add Age to Input

Asked

Viewed 721 times

0

All right with you guys?!

You could help me with a situation. I’m making a simple form, in it I have two inputs, one of them is the Date of Birth and the other is Age. What I am wanting to do is that when I type the date of birth in the first input the second automatically pulls the Age already calculated.

Ex: when I type in Input date of birth : 09/01/2001 the input of the Age automatically bring me 18 years old without pressing a button

In my code, I can actually pull the calculated age by following the above example, man input gosh 18, but I’m not getting to make that pull "18 years old". In case I wish to add "years old" right after the age you’re pulling.

Follow the code:

HTML

<form method="get" action="evento.php?cadastro=true">
    <div>
        <fieldset>
            <legend>DADOS GERAIS</legend>
             <p>Nome * <input type="text" name="nomecompleto" required="true">
                Sexo * <select name="sexo">
                 <option value="">Selecione...</option>
                 <option value="Masculino">Masculino</option>
                 <option value="Feminino">Feminino</option>
             </select>
             Cpf * <input type="text" name="cpf" required="true">
            </p>
            <p>Data <input type="text" name="nascimento" id="data" style="width: 110px;" >
              Idade <input type="text" name="idade" id="idade" disabled style="width: 70px;">
            </p>
        </fieldset>
</div>
    </form>

JS

 document.getElementById("data").addEventListener('change', function() {
  var data = new Date(this.value);
  if(isDate_(this.value) && data.getFullYear() > 1900)
      document.getElementById("idade").value = calculateAge(this.value);
});

function calculateAge(dobString) {
  var dob = new Date(dobString);
  var currentDate = new Date();
  var currentYear = currentDate.getFullYear();
  var birthdayThisYear = new Date(currentYear, dob.getMonth(), dob.getDate());
  var age = currentYear - dob.getFullYear();
  if(birthdayThisYear > currentDate) {
    age--;
  }
  return age;
}

function calcular(data) {
  var data = document.form.nascimento.value;
  alert(data);
  var partes = data.split("/");
  var junta = partes[2]+"-"+partes[1]+"-"+partes[0];
  document.form.idade.value = (calculateAge(junta));
}

var isDate_ = function(input) {
        var status = false;
        if (!input || input.length <= 0) {
          status = false;
        } else {
          var result = new Date(input);
          if (result == 'Invalid Date') {
            status = false;
          } else {
            status = true;
          }
        }
        return status;
}

1 answer

0


The term anos is not being entered because you are only entering the numeric value calculated in input:

document.form.idade.value = (calculateAge(junta))

To include the term anos, you must invite him:

document.form.idade.value = (calculateAge(junta) + ' anos')

I made a functional example (a little simpler) below:

// Função para calcular a idade com base na data de nascimento.
// Origem (SOpt): /questions/5160/como-calcular-a-idade-de-uma-pessoa-com-js-a-partir-da-data-de-nascimento#answer-5162
function getAge(birth) {
  const current = new Date()
  let diff = current.getFullYear() - birth.getFullYear()

  if (
    new Date(current.getFullYear(), current.getMonth(), current.getDate()) <
    new Date(current.getFullYear(), birth.getMonth(), birth.getDate())
  )
    diff--

  return diff
}

// "Pegar" os elementos dos campos:
const birthField = document.querySelector('#birth')
const ageField = document.querySelector('#age')

// Calcular a idade sempre que o campo da data de nascimento for alterado:
birthField.addEventListener('change', (event) => {
  const date = new Date(event.target.value)

  // Note abaixo que estou concatenando a idade calculada com o termo "anos":
  ageField.value = getAge(date) + ' anos'
})
<label>Nascimento:</label>
<input type="date" id="birth" />
<br /><br />
<label>Idade:</label>
<input type="text" id="age" readonly />


P.S.: I can see you’re using the attribute disabled to prevent the age field from being edited. For semantic reasons, prefer to use the attribute readonly in this case, unless you do not want the "age" value to be sent to the server. :)

To learn more, see that answer in Soen.

  • Thanks a lot for the help. I’m a bit new in the programming area, I didn’t know about the readonly I will focus on reading more about the possibilities I have. Thank you for making me evolve one more step in this area.

Browser other questions tagged

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