I have the following code:
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;
}
h3 {
font-family: 'Montserrat';
}
.form-group label {
font-family: Arial;
font-size: 14px;
font-weight: bold;
display: block;
padding: 6px 0;
color: #333;
}
.form-group input {
width: 200px;
margin-bottom: 10px;
color: #333;
padding: 5px;
border: 1px solid #999;
outline: none;
}
<link href="https://fonts.googleapis.com/css?family=Montserrat:100,300,400,500,600,700|Playfair+Display:400,700" rel="stylesheet">
<h3>Informações Pessoais</h3>
<hr>
<form>
<div class="form-group col-md-4">
<label for="nome">Nome:</label>
<input type="text" name="nome" id="nome" class="form-control text-uppercase" placeholder="Digite seu nome">
</div>
<div class="form-group col-md-2">
<label for="data">Data de Nascimento:</label>
<input type="date" name="data" id="data" class="form-control">
</div>
<div class="form-group col-md-1">
<label for="idade">Idade:</label>
<input type="num" name="idade" id="idade" class="form-control" placeholder="Idade" disabled>
</div>
</form>
It returns me the age the way I want it, but I do not know how to do it to return anos
right after age.
The code is ready, all set up, you just need to implement the name right after age, and I do not know how to do that, if someone can read the code and explain me, I appreciate it.