Calculating how many days your are old

In this excercise we will learn about dates in Javascript, how to create an html tag using Javascript, how to set attribute for the new tag created (like setting an ID) and append it to an existing html element.

This function will start when the user press the button start.

First of all we start our JavaScript program by collecting the input from the user about the date. The prompt will ask the user to input the date in the format MM/DD/YYY

var x = prompt("Please Enter your birthdate as MM/DD/YYYY format");

In the next section of the code we will create two dates variable : the first one is based on the input provided by the user.

The second instead represent the current date

var birthdate = new Date(x);
var currentDate= new Date();

At this point we can calculate how many days are between 2 date with the following code

let numberOfDays = (currentDate-birthdate)/(24*60*60*1000);
result=Math.floor(numberOfDays);

Each day has 24 hours, 60 minutes, 60 seconds and each seconds is 1000 milliseconds.

Therefore we need to take the difference between current day and birthdate divide by the result of 24*60*60*1000.

We also want to avoid to display fraction of day and therefore we use the Math.Floor command round it to its floor value.

One other thing that we want to inform the user is in which day she/he was born.

To do this we use the function getDay(). However this function will return the number of day in the week.

If we want to know the day we need to run a small function that will return the name of the day

myday=returnmyDay(birthdate.getDay());
function returnmyDay(val1){
    //This function get the day you were born

    var weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";
    
    var n = weekday[val1];
    return n;
}

The function above receive the number of day of the week as a parameter and then use the number provided to derive the corresponding day of the week.

Let’s have a look now at the html part of this program. We want the number of days and the day of birth displayed in the HTML page.

First of all we create to h3 tags with this command

var myh3 = document.createElement('h3');
var myh3b = document.createElement('h3');

Now that we have the h3 tag we need to assign it a unique ID so that we can bring in the message we want

 myh3.setAttribute('id','display data');
 myh3b.setAttribute('id','display data2');

So now the first tag will have an id “display data”. The second tag instead a “display data2″….sorry for the lack of creativity!

Now we can prepare the text message that we will display in the 2 tag h3 recently created:

var mytext = document.createTextNode('You are '  + result + ' days old');
var mytextb = document.createTextNode('You were born on ' + myday );

At this point we append the 2 text message to each h3 tag with the following command

myh3.appendChild(mytext);
myh3b.appendChild(mytextb);

So far we have attached the text to the Tag h3 but the tag does not have yet a place in the web page.

However if we look at the HTML code we have 2 container

So now we can attach the h3 tags to those 2 containers as shown below

document.getElementById('two').appendChild(myh3);
document.getElementById('three').appendChild(myh3b);

You might recall that previously we have set attributes for each tag and created some id for the h3 tags. However so far we have not used those id. The id created is very handy for the clear button.

We want to have a button that clear the number of days and the day of the week. Let’s have a look at this function:

function clearall(){

    if (booleanchecker==true) {

    document.getElementById('display data').remove();
    document.getElementById('display data2').remove();
    document.getElementById('two').style.borderStyle = "none"; 
    document.getElementById('three').style.borderStyle = "none"; 
    booleanchecker=false;
    
    }
}

As you can see from the code above we are going to remove the h3 tag when the user press the button clear.

As we know that they have an id equal to display data and display date2 we can basically remove the tag h3 and by doing so the web page will no longer show the previous information.

The bookeanchecker is a global variable set to true at the beginning of the fucntion.

The clearall function will work only if the booleanchecker is true.: this will prevent an error in case in the user press twice in a row the clear button that will call the clearall function.


Exercise 002: Step by Step

Let’s review this function step by step

First of all we capture the value included in the InputBox by using its id tag

 let x = document.getElementById("passid");
    pass = x.value;
    numberOfnumbers=0;
    numberOfSpecialChar=0;
    mychar=0;

numberOfSpecialChar and numberOfNumbers are two variables that we will use respectively to measure how many special chars are in the string and how many numbers have been included.

Let’s also set another variable which is type array and includes all the list of special characters .

 myarr = ['!','@','#','$','%','&','*'];

At this point we can start a loop : the objective is to loop through each character of the password the user has provided

 for (i=0;i<pass.length;i++) {
        myCharCode=pass.charCodeAt(i);
        mychar=pass.charAt(i);

        if ( (myCharCode>=48) &amp;&amp; (myCharCode<=59) ) {
                numberOfnumbers++;
        }

        for (y=0; y<7;y++) {

            if (mychar==myarr[y]) {
                numberOfSpecialChar++;
            }
        }

    }

In the line 2 of the above block we use the function charCodeAt to get the ASCII code of each characters included in the password.

In the lines 5-7 we check if the ASCII code is included in the range of numbers code of the ASCII table. The the ASCII code is between 48 and 59 we increase the variable numberOfnumbers.

In the bloc lines 11 to 14 we loop through the myarr variable and check if the char code of the password is equal to one of the char included in the array. If that is the case we increase the variable numberOfSpecialChar

At this point we can verify if all three conditions are met or not. We do that in the following block:

if ( (pass.length>=7) &amp;&amp; (numberOfSpecialChar>=2) &amp;&amp; (numberOfnumbers>=2)) {
        let msg="Password OK"
        document.getElementById("ok").innerHTML=msg;
        document.getElementById("ko").innerHTML="";

    }

If the condition are met we output that the password is ok.

If the condition are not met we output why the password is not valid

else {
        msg="Password is rejected because:";
        msg_specialchar="";
        msg_numberOfnumber="";
        msg_len="";

        if (numberOfSpecialChar<2) {
                msg_specialchar=" the number of special chars is less than 2 - ";
        }

        if (numberOfnumbers<2) {
            msg_numberOfnumber="there are less than 2 numbers - ";
        }

        if (pass.length<7) {
            msg_len=" passowrd is not long at least 7 chars - ";
        }

        msg=msg+ msg_specialchar + msg_numberOfnumber + msg_len;

        msg=msg.slice(0,msg.length-2);
        document.getElementById("ko").innerHTML=msg;
        document.getElementById("ok").innerHTML="";

    }

Something interesting in this exercise is the use of the function charCodeAt(). Interestingly in C you can assign a char to a int variable and the variable will store the code of the char.

Something in JAVA where you can cast,int value = (int) c;, but not in JavaScript which has its own function : charCodeAt().

JS by Exercise 001 – Explanation

First we create  a function called my input

function myinput() {
}

Now we need to capture the input of the user with the prompt command

  let myInp = prompt("Please enter your phrase");

Now that that we have an input from the user consisting in several words we can split this string using the split function and a space (” “) as a delivemeter. We do that by defining a variable x which is an array and we fill it by splitting the string by ” ” and measure how many elements are in the array using length

let x= myInp.split(" ");
let lenarr = x.length;

The following section of the JS code is the one that does the job. First we define 2 variables mystring and total. Both of those variable are type String.

Then we start looping through the array variable x and pass each single word to a variable called myword

So if we have given 3 words as input separated by a space (” “) now we will generate a loop where myword will receive each single word as the loop continues.

Here is any example if we pass the input: javascript is fun.

Now variable x will be composed by an Array of 3 elements.

Now that we have any array we can loop through it. Each single element of the array is passed to the myword variable.

For each word we measure the length again and we start a second loop.

In this second loop we concatenate from char #2 to to the last char (myword.length) and then we add the the first letter (which for java is char[0] by the way)

Then we add the string “ou” and a space char.

let mystring="";
let total="";
    for (i=0;i<lenarr;i++)  {
        var myword=x[i];
        for (y=0;y<x[i].length;y++) {
          mystring= myword.slice(1,myword.length) + myword.slice(0,1) + "ou" + " ";
        }

        total = total + mystring  

So if the input is :

The output by moving the first letter and the end of each word and adding “ou” is:

Here is the full code available to everyone 

function myinput() {
    let myInp = prompt("Please enter your phrase");
    document.getElementById("yourinput").innerHTML="Input->:" + myInp;

    let x= myInp.split(" ");
    let lenarr = x.length;

    let mystring="";
    let total="";
    for (i=0;i<lenarr;i++)  {
        var myword=x[i];
        for (y=0;y<x[i].length;y++) {
          mystring= myword.slice(1,myword.length) + myword.slice(0,1) + "ou" + " ";
        }

        total = total + mystring   
        
    }
    total ="Output->:" + total;
    document.getElementById("yourresult").innerHTML=total;