document.addEventListener('DOMContentLoaded', (event) => {
const inputFecha = document.querySelector("#fechaNac");
const inputEdad = document.getElementById("edad");
inputFecha.addEventListener('change', Edad);
Edad();
function Edad() {
var fechaNacimiento = inputFecha.value;
const fechaActual = new Date();
const anoActual = parseInt(fechaActual.getFullYear());
const mesActual = parseInt(fechaActual.getMonth()) + 1;
const diaActual = parseInt(fechaActual.getDay());
//01-01-2010 2010-01-01
const anoNacimiento = parseInt(String(fechaNacimiento).substring(0, 4));
const mesNacimiento = parseInt(String(fechaNacimiento).substring(5, 7));
const diaNacimiento = parseInt(String(fechaNacimiento).substring(8, 10));
let edad = anoActual - anoNacimiento;
console.log(anoNacimiento);
if (mesActual < mesNacimiento) {
edad--;
} else if (mesActual == mesNacimiento) {
if (diaActual < diaNacimiento) {
edad--;
}
}
inputEdad.value = edad;
}
});
<table class="table">
<thead class="thead-dark">
<tr>
<th hidden>
@Html.DisplayNameFor(model => model.idEntidad)
</th>
<th>
@Html.DisplayNameFor(model => model.nombre)
</th>
<th>
@Html.DisplayNameFor(model => model.fechaConsulta)
</th>
<th></th>
</tr>
</thead>
<tbody id="tbDatos">
@foreach (var item in Model)
{
<tr>
<th hidden>
@Html.DisplayFor(model => item.idEntidad)
</th>
<th>
@Html.DisplayFor(model => item.nombre)
</th>
<th>
@Html.DisplayFor(model => item.fechaConsulta)
</th>
<th>
<a class="fa-solid fa-user-doctor fa-2x" aria-hidden="true" asp-controller="Consulta" asp-action="Atencion" asp-route-id="@item.idEntidad"></a>
</th>
</tr>
}
</tbody>
</table>
<form>
<div class="form-group row">
<input asp-for="idEntidad" class="form-control" type="hidden" id="idEntidad"/>
<input asp-for="fechaNac" class="form-control" id="fechaNac" min="01-01-1930" type="hidden" />
<div class="col-10">
<label asp-for="nombre" class="control-label"></label>
<input asp-for="nombre" class="form-control" id="nombre" readonly />
</div>
<div class="col">
<label asp-for="edad" class="control-label"></label>
<input asp-for="edad" class="form-control" id="edad" disabled />
</div>
</div>
</form>
I have a list, where a list of names are loaded from a database, this list has a button that references the user by id, which takes me to a form loading the user's data, such as name, date of birth and Age should be automatically filled in with the date of birth. In the form, the input where the date of birth and the user's id are loaded are of type hidden and for this reason the age is not calculated. I tested it by removing the hidden from the date of birth input and it calculates the age without problems. I hope now you can understand me