pkarthicbz
pkarthicbz

Reputation: 93

how to update the form field automatically

I am developing a task management system in that i am having the age field in registration form i am having doubt about how to update the field automatically when i click. my script is

<script>
    var a = document.age1.dob.value;
    age = a.getFullYear();
    var curr = new Date();
    year = curr.getFullYear();
    var age1 = year - age;
</script>

i calculated the age and stored it in age1 variable.

<form id="form2" action="#" method="post" name="age1">
<h4><b>Register here</b></h4>
<b>Name</b>: <input type="text" name="name" required="required" placeholder="Your name" pattern="[a-zA-Z0-9\s]+"><br><br>
<b>E-mail</b>: <input type="email" name="email" required="required" placeholder="[email protected]" pattern="[a-z0-9._+%-]+@[a-z0-9.-]+\.[a-z]{2,4}$"><br><br>
<b>Password</b>: <input type="password" name="password" required="required"><br><br>
<b>DOB</b>: <input type="text" name="dob" required placeholder="dd/mm/yyyy" pattern="^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$"><br><br>
<b>Age</b>: <input type="text" name="age" id="age2"><br><br>
<b>Address</b>: <textarea name="address" rows="6" cols="30"></textarea>
<button id="butr" type="submit" class="btn btn-warning">Signup</button>

enter image description here

After i input my DOB in the registration form and click the age field i want the calculated age that i stored it in age1 variable to automatically update the value in age field that i have it in my registration form

Upvotes: 1

Views: 580

Answers (1)

Sree KS
Sree KS

Reputation: 1353

Add an onchange function to dob field

<input type="text" onchange="ageCalculation()" name="dob">

Add this code in your <script>

function ageCalculation(){  
 if(document.age1.dob.value!==""){
     var a = document.age1.dob.value;
     a=new Date(a);
    age = a.getFullYear();
    var curr = new Date();
    year = curr.getFullYear();
    var age1 = year - age;
    document.age1.age.value=age1;
 }
}

Upvotes: 1

Related Questions