South African ID Number Validation using javascript - javascript

I know this question has been asked previously in this forum. However I have a problem when implementing the code.
I want the system to check if the ID number is a valid South African ID number and get the customer's age, gender and date of birth as well.
JavaScript file in my view:
<script type='text/javascript'>
//<![CDATA[
$(window).load(function () {
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4)-1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
});//]]>
</script>
This is where I want ID number to be entered:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<h4>
#ViewBag.Error
#ViewBag.amount#ViewBag.interest#ViewBag.total
</h4>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div id="page-wrapper">
<div class="container-fluid">
<div class="row">
<form role="form">
<div class="form-group">
<div class="row">
<div class="col-md-2">
#Html.LabelFor(m => m.idNumber, "ID Number*")
</div>
<div class="col-md-3">
#Html.ValidationMessageFor(m => m.idNumber)
#Html.TextBoxFor(m => m.idNumber, new {#placeholder = "ID Number", style = "width: 200px;", #class = "form-control"})
</div>
</div>
This is the code that was suggested for the customer to enter his ID number
<div id="error"></div>
<form id="idCheck">
<p>
Enter the ID Number: <input id="idnumber"/>
</p>
<p>
<input type="submit" value="Check"/>
</p>
</form>
<div id="result"></div>
When I try to insert this code out of my #using(Html.BeginForm()) it works perfectly, however when I put it in place of the #Html.TextBoxFor(m => m.idNumber, new {#placeholder = "ID Number", style = "width: 200px;", #class = "form-control"}) it doesn't work.
Any idea why and how I can fix that?

Related

return to zero after reach max value and add the remaining value javascript

sorry i am newbie here
i need some help,
this case like notice a time.
when real time passes input value, then span with id alertLabel will change.
the problem is, if input value plus with input with id Duration will exceed real minutes or hours.
this is my code example.
javascript.js
var alertLabel = document.getElementById("alertLabel");
var less = document.getElementById("lessThan").value.replace(":", "");
var late = document.getElementById("timeIn").value.replace(":", "");
var duration = parseInt(document.getElementById("Duration").value);
var outs = document.getElementById("timesOut").value.replace(":", "");
var lessInt = parseInt(less);
var lateInt = parseInt(late);
var outsInt = parseInt(outs);
var durationOut = outsInt + duration; // this will be exceed
var durationIn = lateInt + duration; // this will be exceed
function getAlert() {
let times = new Date();
let sh = times.getHours() + "";
let sm = times.getMinutes() + "";
let ss = times.getSeconds() + "";
let shLong = sh.length == 1 ? "0" + sh : sh;
let smLong = sm.length == 1 ? "0" + sm : sm;
let ssLong = ss.length == 1 ? "0" + ss : ss;
let shSm = shLong + smLong;
document.getElementById("clock").innerHTML = shLong + ":" + smLong + ":" + ssLong;
if (shSm >= outsInt && shSm < durationOut) {
alertLabel.innerHTML = "OUT!!";
} else if (shSm >= lessInt && shSm < lateInt) {
alertLabel.innerHTML = "hurry up, don't be late!!";
} else if (shSm >= lateInt && shSm < durationIn) {
alertLabel.innerHTML = "LATE!!";
} else {
if (shLong >= 21 || shLong <= 4) {
alertLabel.innerHTML = "good dream tonight !!";
} else if (shLong >= 5 && shLong <= 11) {
alertLabel.innerHTML = "spirit Morning !!";
} else if (shLong >= 12 && shLong <= 17) {
alertLabel.innerHTML = "happy Noon !!";
} else if (shLong >= 18 && shLong <= 20) {
alertLabel.innerHTML = "nice evening !!";
}
}
}
<!doctype html>
<html>
<head>
<title></title>
</head>
<body onload="getAlert();setInterval('getAlert()',1000)">
<span id="clock"></span>
<span id="alertLabel"></span>
<div></div>
<input class="" type="text" id="lessThan" value="13:45" name="lessThan"> <!-- when time to in is near -->
<input class="" type="text" id="timeIn" value="13:48" name="timeIn"> <!-- time in and get alert Late -->
<input type="text" id="timesOut" value="13:55" name="timesOut"> <!-- value time to out and get alert Out -->
<input type="text" name="Duration" id="Duration" value="5"> <!-- duration alert for id timeIn and timesOut if more than 100 is the problem, this input as minute -->
</body>
</html>
this is my last try, example in input id timeIn
var a = document.getElementById("timeIn").value.split(":");
for (var i = 0; i < duration; i++){
var b = parseInt(a[0]); // this for hours
var c = parseInt(a[1]); // this for minutes
var x = c + i;
if (x >= 60){
var n = b + 1;
x = x-60;
}
console.log(x);
}
in my last try, in log var x return to zero just once
and the question is, if input value with id duration more than 100, how looping, if each var x reach value (60) his return to zero and var c plus 1 each var x reach 60.
maybe anyone have an easier one to solve this case.
sorry if the explanation is unclear.

Compare generated letter with user input

My problem is as followed: I want to realise a (really) small application in which I want to generate a letter (between A and E) and compare it with the user input made afterwards. If the user input is not the same as the generated letter a message should pop up, which tells the user that he made the wrong choice. If the user made the right choice, a counter gets +1 and if the user reaches at least 3 of 5 points, he wins a prize. The user has 3 tries before the script ends.
The hurdle is that my main focus lies on php. My knowledge in JavaScript is not that much.
So my script won't do anything when the user types his answer in.
SOLVED!
The Code beneath is the solution.
String.prototype.last = function(){
return this[this.length - 1]
}
;(function() {
var score = 0;
var text = "";
var possible = "ABCDE";
var noOfTries = 5;
function generateCharacter() {
var index = Math.floor(Math.random() * 100) % possible.length;
text = possible[index];
possible = possible.slice(0, index) + possible.slice(index+1);
alert(text);
return text;
}
function validate(string) {
return (string || "").trim().last() === text.last();
}
function handleChange(){
var valid = validate(this.value);
if(valid){
score++;
alert("Richtig!");
}else{
alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!");
}
console.log(this.value.length === noOfTries)
this.value.length === noOfTries ? notify() : generateCharacter();
}
function notify(){
if(score == 0) {
alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?");
}else if(score >= 1 && score <3){
alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?");
}else if(score >= 3 && score <= 5) {
alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!");
}
}
function registerEvent(){
document.getElementById('which').addEventListener('keyup', handleChange);
}
registerEvent();
generateCharacter();
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="which">Antwort? </label>
<input type="text" name="which" id="which" placeholder="#" style="width: 9px;">
And here's the fiddle: Compare generated string with user input

Verify ID Number using javascript

I am trying to verify the south african ID NUMBER. I am not fluent with javascript.
I have the following code:
The HTML and Javascript
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
<title>the man</title>
<script>
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
</script>
</head>
The Body:
<body>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
Unfortunately I am not getting any error output. Please Assist
If this is the entire code, you are missing the closing head tag after script, I ran it and it worked as far as displaying different error messages with that cleaned up.
Edit- also added compiled code below which has document.ready shorthand.
<!DOCTYPE html>
<head>
<title>the man</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
});
</script>
</head>
<body>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
There were two proposed solutions and both of them would work.
First to remove script from the head section. (I guess you both placed </head> in different places, and that's why for one of you the submit attached correctly but not for the other)
<HTML>
<head>
<title>the man</title>
</head>
<body>
<script src="jquery-1.12.0.min.js"></script>
<script> //your code</script>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
And the other to wrap all your code in
$(document).ready(wrapper);
function wrapper(){
function Validate() {
//your code
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
}
Why does the first solution work? First we render <head> so when your code is run
$('#idCheck').submit(Validate);
cannot be attached because the dom element does not exist yet. If we place the code in the execution is delayed.
Why does the second solution work? We wait until all page is rendered; only then do we execute our function that contains the same event attachment ($('#idCheck').submit(Validate);).

Javascript total return NaN for 4 digits num

Here is the javascript for calculating the price of the item the problem is that
whenever the price is 4 digits the value that return is NaN.
here's my hidden field for the price:
<input type="hidden" name="price" id="price"class="price" value="4500"readonly >
here's for my quantity field
<input type="number" name="quant" id="quant" value="2" />
here's for my shipment fee
<select id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select
here's for the total price
<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly>
Script for changing the value of shipment
<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
var value = parseInt(this.value, 20),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
</script>
Calculating all the values
function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
$("#price,#quant,#shipment").keyup(function () {
if(+myFunction3() =="" )
{
$('#demo').val(0);
}
else if($('#trigger')=="checked") //this is the problem
{
$('#demo').val($('#price').val() * $('#quant').val() ;
}
else
{
$('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
}
});
</script>
Not sure if this was just typed incorrectly in here, but you have a syntax error (missing closing parenthesis) near the problem area:
$('#demo').val($('#price').val() * $('#quant').val() ;
Should be:
$('#demo').val($('#price').val() * $('#quant').val());
I think it would be much better to ensure you aren't working with strings before you do math on them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);
You could go further and ensure that neither of them are NaN prior to working with them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
$('#demo').val(price * quantity);
} else {
alert('Please enter numbers only!');
}

Age Calculator in Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I have this codes, this code must be able to compute the age of the user and It must be displayed on the text box provided and the age must change if the user changed his birth-date.
but this code does not work, it doesn't display the computed age in the textbox.
<input name= "date" type="text" readonly="readonly" />
<select id="Ultra" onchange="run()">
<option value="11/15/991">1991-11-15</option>
<option value="10/23/1992">1992-10-23</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br>
<script type="text/javascript">
function run() {
var birth = document.getElementById("Ultra").value;
var check = new Date();
var milliDay = 1000 * 60 * 60 * 24;
var AgeinDay = (check - birth) / milliday;
var ComputAge = Math.floor(AgeinDay / 365 );
var age = ComputAge / 365;
document.getElementById("srt").value = age;
}
</script>
Here is a look to complete Age Calculation in JavaScript:
<body onload="getAge()">
<h1 id="age" ></h1>
<script>
function calculateAge(dob) {
var now = new Date();
var dob = new Date(dob);
var year=now.getYear()-dob.getYear();
var month=now.getMonth()-dob.getMonth();
if(month<0){
month=now.getMonth()+12-dob.getMonth();
year=year-1;
}
var day=now.getDate()-dob.getDate();
if(day<0){
var monthNumber=dob.getMonth();
var fullDate=getFullDate(monthNumber);
day=now.getDate()+fullDate-dob.getDate();
month=month-1;
}
return year+" Years, "+month+" Months, "+day+" Days!";
};
function getFullDate(x){
switch(x){
case 0:
return 31;
break;
case 1:
return 28;
break;
case 2:
return 31;
break;
case 3:
return 30;
break;
case 4:
return 31;
break;
case 5:
return 30;
break;
case 6:
return 31;
break;
case 7:
return 31;
break;
case 8:
return 30;
break;
case 9:
return 31;
break;
case 10:
return 30;
break;
case 11:
return 31;
}
}
function getAge(){
x=prompt("Please Enter Your Date of Birth in format (yyyy-mm-dd): ","");
x=new Date(x);
document.getElementById("age").innerHTML="Your age is: "+calculateAge(x);
}
</script>
</body>
try this..
function run() {
var birth = new Date(document.getElementById("Ultra").value);
var curr = new Date();
var diff = curr.getTime() - birth.getTime();
document.getElementById("srt").value = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
There were three errors in your code, see the comments inline below:
The year value of first option was 991 instead of 1991, might cause you to think the calculation is wrong.
String containing date that is being assigned to birth variable has to be passed as parameter to Date() function to create a date object that can be used with the current date object below it.
Variable milliDay was declared, then you were trying to use milliday (wrong case D).
<input name= "date" type="text" readonly="readonly" />
<select id="Ultra" onchange="run()">
<option value="11/15/1991">1991-11-15</option> <!-- year value was 991 instead of 1991, might cause you to think the calculation is wrong -->
<option value="10/23/1992">1992-10-23</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br>
<script type="text/javascript">
function run() {
var birth = new Date(document.getElementById("Ultra").value); //string containing date has to be passed as parameter to Date() function to create a date object that can be used with the current date object below
var check = new Date();
var milliDay = 1000 * 60 * 60 * 24;
var AgeinDay = (check - birth) / milliDay; //variable here was milliday all small case, declared above as milliDay with a capital D
var ComputAge = Math.floor(AgeinDay / 365 );
var age = ComputAge / 365;
document.getElementById("srt").value = age;
}
</script>
This will return the following values assuming the first option is selected:
age: 0.057534246575342465
ComputAge: 21
Are you just trying to get the age in years, or months, days hours too?
Below is Advanced code for Age calculator in JavaScript
<h1>Age Calculator Tool</h1>
<h2>Hey Dear, What's your name? <br /><input type = "text" placeholder = "Enter Your Name" autofocus/></h2>
<div id = "disBlock">
<p id = "disBD"></p>
<p id = "display"></p>
<p id = "time"></p>
</div>
<div id = "postCredit">
<p id = "credit"></p>
<a id = "about" href="#" target="_blank">Know More About Me</a>
</div>
<form>
<label>Enter Your Date of Birth: <input
type = "date"/></label><br />
<button type = "button">Calculate</button>
<button type = "reset">Reset</button>
</form>
<script>
let display = document.getElementById("display");
let input = document.getElementsByTagName("input");
let button = document.getElementsByTagName("button");
let time = document.getElementById("time");
let disBlock = document.getElementById("disBlock");
let disBD = document.getElementById("disBD");
let creditBlock = document.getElementById("postCredit");
let credit = document.getElementById("credit");
let about = document.getElementById("about");
disBlock.style.display = "none";
creditBlock.style.display = "none";
let dob = new Date(), today = new Date(), calTime;
function samay() {
let d = new Date();
time.innerHTML = d.getHours() + " Hours, " +
d.getMinutes() + " Minutes, " + d.getSeconds() + " Seconds Old";
}
function calculate() {
disBlock.style.display = "block";
creditBlock.style.display = "block";
credit.innerHTML = "Thank You For Visiting<br>Our website website.com";
let x = input[1].value.split("-");
dob.setDate(x[2]);
dob.setMonth(x[1] - 1);
dob.setFullYear(x[0]);
let year, month, day, HBD;
day = (function() {
if(today.getDate() > dob.getDate()) {
return today.getDate() - dob.getDate() - 1;
}
else if(today.getDate() == dob.getDate()) {
return today.getDate() - dob.getDate();
}
else {
let calDate = new Date(dob.getFullYear(), dob.getMonth() + 1, 0);
return (today.getDate() + calDate.getDate()) - dob.getDate() - 1;
}
}());
month = (function() {
if(today.getMonth() >= dob.getMonth()) {
if(today.getDate() >= dob.getDate()) {
return today.getMonth() - dob.getMonth();
}
else {
if((today.getMonth() - 1) >= dob.getMonth()) {
return (today.getMonth() - 1) - dob.getMonth();
}
else {
return ((today.getMonth() - 1) + 12) - dob.getMonth();
}
}
}
else {
if(today.getDate() >= dob.getDate()) {
return (today.getMonth() + 12) - dob.getMonth();
}
else {
return ((today.getMonth() - 1) + 12) - dob.getMonth();
}
}
}());
year = (function() {
if(dob.getMonth() == today.getMonth()) {
if(dob.getDate() > today.getDate()) {
return (today.getFullYear() - 1) - dob.getFullYear();
}
else {
return today.getFullYear() - dob.getFullYear();
}
}
else {
if(dob.getMonth() > today.getMonth()) {
return (today.getFullYear() - 1) - dob.getFullYear();
}
else {
return today.getFullYear() - dob.getFullYear();
}
}
}());
HBD = (function(){
if(today.getMonth() == dob.getMonth()) {
if(today.getDate() == dob.getDate()) {
disBD.innerHTML = "OMG it's your Birthday<br>Happy Birthday To You<br>";
}
else {
disBD.innerHTML = "";
}
}
else {
disBD.innerHTML = "";
}
}());
display.innerHTML = "Hi Dear " + input[0].value + ", <br/>You are " + year + " Years, " + month +
" Months, " + day + " Days, ";
calTime = setInterval(samay, 1000);
}
button[0].onclick = calculate;//when calculate button is clicked
function reset() {
input[0].focus();
display.innerHTML = "";
time.innerHTML = null;
clearInterval(calTime);
disBlock.style.display = "none";
creditBlock.style.display = "none";
}
button[1].onclick = reset;//when the reset button is clicked
</script>
More source code from : https://www.technicalarp.com/2021/11/javascript-age-calculator-script-html-code.html

Categories

Resources