Articles by "How To"
Showing posts with label How To. Show all posts
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

ID and Class attributes are the most common selectors that widely used to target the HTML DOM while working with JavaScript. Have you ever thought why we mostly prefer to use the id and class while many of the methods are available to target the HTML Elements in JavaScript?

First of all, we look at all the methods to target the HTML Elements using JavaScript.

For reference you can check the multiple examples below.

How to target HTML elements using ‘id’?



    <div id="test"></div>
    <script>
        //we want to print "Hello World inside div"
        document.getElementById("test").innerHTML="Hello World!";
    </script>
Try Yourself

In this method we target the Single HTML element within the DOM tree using its ID attribute. While using ID, it always returns a single node of HTML DOM.

The most important thing is that using two or more HTML elements with the same ID on the same web page can produce the unexpected error, therefore, we should be careful using the ID attribute while creating the web page.

How to target HTML Elements using ‘class’?



    <!--Different HTML tags with same classes-->
    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    
    <script>
        document.getElementsByClassName("test")[0].innerHTML="This Heading";
        document.getElementsByClassName("test")[1].innerHTML="This is div";
        document.getElementsByClassName("test")[2].innerHTML="This is paragraph";
        document.getElementsByClassName("test")[3].innerHTML="This is span";
    </script>
Try Yourself

In this method we target one or more HTML Elements with the same class name. When we target HTML Elements with the class name, each HTML element with the same class becomes the part of that class, it returns a list of nodes (referred to as NodeList in the console) instead of a single node where each node can be referred with the index number like given in above example.

The index number of each node is decided by its appearance on the web page. For e.g. the index of the very first node is referred to as [0] and second as [1] and so on. If the position of any node is changed on the webpage then its index will be also changed accordingly and it might affect the index of rest upcoming nodes also.

Even we target a single element with the class name, it returns a list of nodes but the difference is that there is only a single node present in that list.

Therefore it is a better idea to use class names but in a structured way.

We will study more about classes in further chapters

How to target HTML Elements using ‘tag name’?



    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    <span class="test"></span>
    <script>
        document.getElementsByTagName("H1")[0].innerHTML="This Heading";
        document.getElementsByTagName("DIV")[0].innerHTML="This is div";
        document.getElementsByTagName("P")[0].innerHTML="This is paragraph";
        document.getElementsByTagName("SPAN")[0].innerHTML="This is first span";
        document.getElementsByTagName("SPAN")[1].innerHTML="This is second span";
    </script>
Try Yourself

In this method we target one or more HTML elements with their tag name. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

How to target HTML Elements using the ‘name’ attribute?



    <!--Different HTML tags with same classes-->
    <form action="">
        <div><input type="text" name="fname" placeholder="first name" value="John"/></div><br/>
        <div><input type="text" name="lname" placeholder="last name" value="Doe"/></div><br/>
        <div><input type="email" name="email" placeholder="email" value="john@progrramers.com"/></div><br/>
        <div><input type="url" name="website" placeholder="website" value="https://progrramers.com"/></div><br/>
        <div><input type="button" name="submit" value="Save" onclick="formdata()"/></div><br/>
    </form>
    <p name="test"></p>
    <script>
        function formdata(){
            var fname=document.getElementsByName('fname')[0].value;
            var lname=document.getElementsByName('lname')[0].value;
            var email=document.getElementsByName('email')[0].value;
            var website=document.getElementsByName('website')[0].value;
            document.getElementsByName("test")[0].innerHTML = "First name: "+fname+"<br/>Last name: "+lname+"<br/>Email: "+email+"<br/>Website: "+website;
        }
    </script>
Try Yourself

In this method we target one or more HTML elements with their name attribute. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

Note: Name attribute’s value also can be accessible in the post method of server-side scripts like PHP. We will deal with it during the tutorials of server-side scripts.

How to target HTML Elements using the ‘querySelector’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelector('#test_id').innerHTML="This is First DIV Element.";
        document.querySelector('.test_class').innerHTML="This is Second DIV Element.";
    </script>
Try Yourself

In this method we target single HTML Element using CSS selector. In CSS if we want to target element with tag name we use the tag name, or if we want to use the ID or Class then we use ‘#’ with ID and ‘.’ with the class name. Similarly we can use CSS all selector to with query selector method.

Likewise ID case, it returns only the first node present on the web page.

How to target HTML Elements using ‘querySelectorAll’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelectorAll('#test_id')[0].innerHTML="This is First DIV Element.";
        document.querySelectorAll('.test_class')[0].innerHTML="This is Second DIV Element.";
        document.querySelectorAll('.test_class')[1].innerHTML="This is Third DIV Element.";
    
        console.log(document.querySelectorAll("DIV"));
    </script>
Try Yourself

This method is the same as the query selector method but in this method we target one or more HTML Elements using CSS selector and it returns a set the node list where each node can be accessed by the specific index number.

You have seen all the examples given above. These are the methods to target the HTML DOM or HTML DOMs in JavaScript. You must know a few things also which are mentioned below

  1. The methods that return the list of nodes can be looped. Check example 7 ahead.
  2. Although node list can be looped they aren’t referred to as an array because array must have few methods like push, splice & sort but not in case of node list.
  3. ID, Class, and Name are the attributes that can be directly accessed in JavaScript. For reference Check example 8.
  4. Id & name attribute can have one value at a time and can be used only once on the webpage but the class can have multiple values at the same time. The value should be separated by space. For e.g. class=”container box primary”. There are three different classes in the example container, box & primary.

How to apply loop on a NodeList?


Code Copied
<div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <script>
        var el=document.querySelectorAll('.test'),n=1;
        el.forEach(element => {
            element.innerHTML="This is DIV No. "+(n++);
        });
    </script>
Try Yourself

How to Find ID, Class & Name Attribute Values?


<div id="test_id">This DIV has id Attribute</div>
    <!--Class can have multiple value-->
    <div class="test_class1 test_class2 test_class3">This DIV has class Attribute</div>
    <div name="test_name">This DIV has name Attribute</div>


    <p id="result_1"></p>
    <p id="result_2"></p>
    <p id="result_3"></p>

    <script>
        document.getElementById("result_1").innerHTML = document.getElementById("test_id").id;
        document.getElementById("result_2").innerHTML = document.getElementsByClassName("test_class1")[0].className;
        document.getElementById("result_3").innerHTML = document.getElementsByName("test_name")[0].getAttribute("name");
    </script>
Try Yourself
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

In the previous chapter of JavaScript Tutorials, we have learned about what JavaScript can do? Now we are about to learn that How and Where to use JavaScript on an HTML Document?

How to use JavaScript on HTML Documents?

Before we go forward we need to understand the most important thing and that is ‘How a web page is parsed on a web browser? This question is most important because until unless we don’t understand the working principle of a webpage, we can’t develop it with any client-side scripting language like JavaScript.

We already know that JavaScript manipulates the HTML DOM by changing its inner HTML, inner Text, values, and style. JavaScript is used to perform a certain task or chain of the task and execute it on the browser by changing the status of HTML DOMs. To do so we have to find and target the specific HTML DOM with various methods that we will learn in upcoming chapters. 

To understand the above sentences we need to check the below example.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of JavaScript</title>
</head>
<body>
    <div id="test"></div>
    <script>
        document.getElementById("test").innerHTML = "Hello World!";
    </script>
</body>
</html>
        
Try Yourself

What we see in the example above given. There are two things in the above example

The first thing we see there is an HTML document contains a DIV element with an attribute named ID. The value of the ID is ‘test’. We required printing Hello World inside the DIV element dynamically using JavaScript when a web page is loaded.

Second thing, there is also a script tag just before the end of body tag where are some codes are written which is not likely HTML codes. Actually the codes written in script tags are JavaScript. JavaScript codes are written between <script> tags on HTML documents.

Now to understand the working principle of the above example you can copy and paste the above code in your favorite HTML editor and save the file with .html file extension and run into your favorite browser. You will see ‘Hello World’ printed on the web page.

On the web page loading process, we simply target the HTML DIV tag by its ID using “document.getElementById()” method and setting the value ‘Hello World’ of its ‘innerText’ so that when the web page completely falls on the browser it prints ‘Hello World’ text.

This is how we target the HTML DOM on an HTML web page using JavaScript. This was only an example but in professional projects, we do something like this on a large scale. We will sure study that in this tutorial series.

 

Why & when use type attribute within <script> tags?

Now we know that JavaScript codes are written inside <script> tags. Let’s check a few another example given below

JavaScript codes with a type attribute in script tags


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Use of Type Attribute</title>
</head>
<body>
    <div id="test"></div>
    <script type="text/javascript">
        document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
    </script>
</body>
</html>
        
Try Yourself

JavaScript codes without type attribute in script tags


<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Example of HTML5 Version Doctype</title>
</head>
<body>
     <div id="test"></div>
     <script>
          document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
     </script>
</body>
</html>
Try Yourself

In both examples can you see the difference? You can see in example 2 <script> tag is used with type attribute and in example no 3 <script> tag is used without type attribute.

This is happening because of the HTML Document version. Before HTML version 5 JavaScript is not the default scripting language of HTML so we must specify the type of scripting language. Older browsers are not able to find the type of script language therefore JavaScript might not work.

But since HTML 5th version JavaScript is becoming the default scripting language, therefore, we are not forced to use type attribute in script tag while working with JavaScript.

Note: Above both examples can work in the latest browsers without type attribute. The problem comes with only older browsers.

Where to use JavaScript on HTML Documents?

Above all the examples are demonstrating to us how to use JavaScript on an HTML Document. Now let’s move on Where to use JavaScript on HTML Documents?

Before we go ahead first we need to understand how an HTML Document is parsed on a browser and become a web page.  Usually, HTML Document is parsed on a browser top to bottom and left to right. It means that the most top line of the document is parsed first into left to right direction therefore whole HTML DOMs must be parsed over web browsers before JavaScript functions are called.

If it doesn’t happen then the browser console will throw the script error and it can be case wise different. Another thing is that by default JavaScript declared functions and variables are stored on the top level in primary memory while launching the web page whether they are declared on top of page or bottom of the page, therefore, we should not worry about where we are trying to keep our JavaScript codes on HTML document. Therefore we can place JavaScript declared functions and variable between the <head> tags like the below-mentioned example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Declared Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button onclick="myFunction()">Click</button>
</body>
</html>
        
Try Yourself

We should worry about only JavaScript calling functions which must be executed at the most end of part of the web page so that All HTML DOMs can found easily found which are targeted by JavaScript. It is good practice to place JavaScript codes on the most bottom part of HTML <body> tags, mention like below example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Calling Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>

    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        
Try Yourself

Also, it is observed that placing JavaScript code at the bottom of <body> tags improves the display speed because script interpretation slows down the display.

Above shown examples are a type of internal JavaScript but there is another type of JavaScript also which can improve the development speed without harming the performance of the web site.

What are the types of placement of JavaScript on an HTML Document?

  1. Internal JavaScript
  2. External JavaScript

What is Internal JavaScript?

Internal JavaScript is a practice in which all the JavaScript codes are written separately in every document. The drawback of this practice is that we have to write a similar type of code again and again which slows down the development speed. All the above show examples are a type of internal JavaScript.

What is External JavaScript?

In this practice JavaScript codes are written in a separate file which has the file extension “.js”. To embed the external JavaScript file on the web pages we have to use <script> tags with a specific attribute named ‘src’ which holds the location path of the external JavaScript file.

Take a look at a below-given example. This example is created using jQuery CDN. You will learn jQuery in further chapters.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Absolute Path Over jQuery Content Delivery Network (CDN)</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        $(document).ready(function(){
            $('#test-button').click(function(){
            $('#test').html("Hello World!")
            });
        });
    </script>
</body>
</html>
        
Try Yourself

Few points must be noticed while creating an external JavaScript file.

  1. JavaScript file created with .js extension is not a web page rather a script page.
  2. JavaScript file cannot contain the <script> tags.
  3. Multiple JavaScript pages can be used on a single HTML document.
  4. It is important to declare the HTML web page doctype because before HTML5 JavaScript not default scripting language. We have to specify the ‘type’ attribute in <script> tags to make active scripting language.

What are the advantages of external JavaScript?

  1. HTML and JavaScript codes are separated while using external JavaScript
  2. JavaScript code which required to be executed again & again on different pages is not required to write multiple times.
  3. It makes developers easy to maintain and develop the program fast.
  4. You can use different specialist code editor at the same time. For example, Notepad++ is best for HTML, and VSCode is best suitable for JavaScript.
  5. External JavaScript code can be cached into the client device therefore cached JavaScript file can speed up the page load.

Using absolute and relative path reference for external JavaScript

 External JavaScript files can embed on HTML documents using relative or absolute path references which show below in the examples.

To understand relative or absolute file path learn HTML5 Tutorial - HTML File Path


//declared functions and variables
  var x = "You have clicked the button."
  function myFunction(){
  document.getElementById('test').innerHTML=x;
}
        


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of External JS file using absolute path</title>
    <script src="script.js"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        

Copy the JavaScript codes given in example 7 and paste into your favorite text editor and save as script.js and after that once again create a new file in the text editor and copy HTML codes from example 8 and paste into the text editor and save the document as 'example8.html'. Both the files must be located into same directory. 

After that run the example8.html file in the browser, you will see on the web page there is a button named 'Click'. When you click the button then a sentence 'You have clicked the button' will appear on the screen. This means the JavaScript codes written in a separate file is embedded properly and working fine.

On HTML file example8.html you can see <script> tag with 'src' attribute having the value 'script.js' which the name of JavaScript file. Actually the source of JavaScript is fetching on the web page from that file which is embedded with HTML document through a 'Relative path'.

Similarly, look back into example 6 where you can find <script> tag with 'src' attribute having a value 'https://code.jquery.com/jquery-3.5.1.min.js'. It is an example of an absolute URL. To know more about the relative and the absolute path you have to read our another topic HTML5 Tutorial - HTML File Path.

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello programmers! This is a new “JavaScript How To” post which describes ‘How to create Cascading Dropdown Using Plain JS’. This is an example of multiple dependent dropdown lists. Multiple dependent cascading dropdown lists are very useful when you want to display the data in specific categories. You can change drop down options based on another dropdown lists.

First of all, you can click on Try yourself button in below example and check what are we going to create and after that you will find all the require source code of this project. You can also bookmark the repository of progrramers GitHub community where you can find and download the source code of other projects.
If you like our posts please give thumbs up  πŸ‘ on our Facebook page and also share with your near n dears.



Diagram

In this example we are assuming that there is a school. It has multiple class rooms, every class room contains multiple sections, every section contains multiple subjects and at last every section period will held on a different room. You can see the whole scenario in below image given for the reference.

How to create Cascading Dropdown Using Plain JS - progrramers
How to create Cascading Dropdown Using Plain JS - progrramers

The data will be in tree structure which is used to parse as options in 'SELECT' elements. Let's see the work flow of the final product.

Work Flow 

  1. Classes names only append into select element onload first.
  2. When Selecting a Class then section options will append, available with that class. Same work flow for sections, subjects and rooms.
  3. When Class gets changed then sections, subjects and rooms also get reset. Same work flow for sections, subjects and rooms. Synopsis when a drop down element updated then all next siblings also gets reset.
Now you can copy the code and paste it into your favorite editor and save as ‘anyname.html’ and run into your favorite browser. Analyze the code and if you are getting any problem then feel free to write down into the comment section I’ll try to be more specific into the answers.

You can also get this code on github : How to create Cascading Dropdown Using Plain JS.html

How to create Cascading Dropdown Using Plain JS :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{box-sizing: border-box;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}
        .classform{border: 5px groove #00acf0;background: #c5c5c5;border-radius: 4px;}
        div{padding:5px;}
        .classform>div{width:450px;display:block;margin-left:auto;margin-right:auto;}/*for responsive look*/
        label{background: #00acf0;color:rgb(255, 255, 255);text-shadow:1px 1px 1px #777}
        label,select{display:inline-block;padding:6px;border-radius:3px}
        label{width:100px;}
        select{width:250px;}
    </style>
</head>
<body>
    <div class="classform">
        <div><label for="class">Class: </label> <select name="class" id="class"></select></div>
        <div><label for="section">Section: </label> <select name="section" id="section"></select></div>
        <div><label for="subject">Subject: </label> <select name="subject" id="subject"></select></div>
        <div><label for="room">Room: </label> <select name="room" id="room"></select></div>
    </div><hr/>
    <a href="https://www.facebook.com/theprogrramers">Follow us on Facebook Page</a>
    <script>
        //class structure data in JS object format
        var structure = [
                {label:"class",value:"1",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                ]},
                {label:"class",value:"2",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Sanskrit",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"English",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Civics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Geography",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Economics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (C)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (D)",child:[]},
                        ]}
                    ]}
                ]},
                {label:"class",value:"3",child:[
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"3 (A)",child:[]},
                        ]}
                    ]}
                ]},
            ];
        //global variable declaration to store value stepwise
        var cindex, sindex, jindex;
        //calling funfction onload
        window.onload = function(){
            classstrucure(structure, document.querySelectorAll('[name=class]'));
        }
        document.querySelector('body').addEventListener('change',function(e){
            if(e.target.tagName.toLowerCase() == "select"){
                if(e.target.value!==""){
                    //check of nextsibling is null or not 
                    nextsibling = e.target.closest('DIV').nextSibling.nextSibling;
                    if(nextsibling!==null){
                        var _nameAttr=e.target.getAttribute("name");
                        var nextElm = nextsibling.querySelectorAll('SELECT');
                        //for your project only you have to change the attributes name
                        if(_nameAttr==='class'){
                            cindex = structure.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='section'){
                            sindex = structure[cindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='subject'){
                            jindex = structure[cindex].child[sindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child[jindex].child, nextElm);
                        }
                    }
                }else{
                    //e.target.value is empty then same function will fire with defferent parameters
                    clearsturcture(e.target.closest('DIV').nextSibling);
                }
            }
        });
        //function create the structure of class step wise
        function classstrucure(data, el){
            //first clear all the select element onload
            //clear all next sibling accept itself
            el.forEach(element => {
                clearsturcture(element.closest('DIV')); 
            });
           // clearsturcture(el[0].closest('DIV'));            
            var opt = '<option value="">--Select--</option>';
            //creating options elemnet
            for(var i=0;i<data.length;i++){
                opt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
            }
            //appending option on each element
            el.forEach(element => {
                element.innerHTML = opt;
            });
        }
        //clear all the next drop down element after itself
        function clearsturcture(parentEl){
            while (parentEl) {
                if(parentEl.tagName !== undefined){
                    //appending initial option on every next sibling
                    parentEl.querySelector('SELECT').innerHTML = '<option>--Select--</option>';
                }
                //looping through last existing sibling and target
                parentEl = parentEl.nextSibling;
            }
        }
    </script>
</body>
</html>
Try Yourself

Related Topics

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

What is MongoDB ObjectId() ?

ObjectIds are small unique ID that generated very fast and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the seconds since the Unix epoch, 5-byte random value, and last 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

MongoDB ObjectId is generated by MongoDB Drivers and the Server using a default Algorithm. By default typeof MongoDB ObjectId is object.

MongoDB ObjectId 12 bytes can be break up in to following:

Size Description
4 Bytes 4-byte value representing the seconds since the Unix epoch
3 Bytes 3-byte machine identifier
2 Bytes 2-byte process id
3 Bytes 3-byte counter, starting with a random value

Above is a description of MongoDB ObjectId. Most of the time developers requires unique id of the objects to be rendered on web page. In MongoDB ObjectId are the primary key and best for using as unique ID. Therefore here on the progrramers.com we are giving the solution for ‘How to get lowercase hexadecimal mongodb _id string from ObjectId() in MongoDB ?

Below is the example database which we are using the MongoDB tutorial :



> db.cars.find().toArray();
[
{
"_id" : ObjectId("5d53065a520ea88ac000e981"),
"name" : "Ford",
"color" : "blue",
"weight" : "300KG"
},
{
"_id" : ObjectId("5d53066a520ea88ac000e982"),
"name" : "Opel",
"color" : "red"
},
{
"_id" : ObjectId("5d530677520ea88ac000e983"),
"name" : "Mustang",
"color" : "silver"
},
{
"_id" : ObjectId("5d53069f520ea88ac000e984"),
"name" : "porsche",
"color" : "black"
}
]
>


There are many methods available that can be use to extract the lowercase hexadecimal mongodb _id string from MongoDB ObjectId. We will try to approach all possible ways by using MongoDB methods and JavaScript methods as well.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘valueOf()’ method

Syntax : db.collectionname.findOne()._id.valueOf()

> db.cars.findOne()._id.valueOf();
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object in form of ‘property : value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘str’ method


Syntax : db.collectionname.findOne()._id.str

> db.cars.findOne()._id.str;
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object like above mentioned method e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that ‘str’  method extract the lowercase hexadecimal mongodb _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get value of the ObjectId() in MongoDB using stored functions


There is a special system collection named system.js that can store JavaScript functions for reuse. We can latter call the function using ‘db.eval()’ or ‘db.loadServerScripts()’ methods and get results.

Syntax : db.system.js.save({_id:”functionname”,value:function(parameters){//code here}})

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()")
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>

Explanation

Below example first stores the object in ‘doc’ variable in form of ‘property: value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’. The whole function expression stored in variable and saved in ‘system.js’ collection.
Note : db.eval is deprecated from MongoDB version 3.2 but finally db.eval is removed from MongDB version 4.2 but db.loadServerScripts() method can be used instead

Above stored function is called using ‘db.eval()’ method, below is another method to call stored function in MongoDB shell.

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.loadServerScripts()
> getObjectID()
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>



How to get value of the ObjectId() in MongoDB using plain JavaScript

MongoDB stored functions uses pure JavaScript so it is possible to apply various JavaScript methods to perform a certain task. Now we will see how to get the hexadecimal string in bulk using ‘Array.map()’ function from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){return i._id.valueOf()});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using forEach loop

In this example we will see how to use forEach loop in MongoDB Stored function to extract hexadecimal MngoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... doc.forEach(element => {
... myArr.push(element._id.valueOf());
... });
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using for Loop

In this example we will see how to use for loop in MongoDB Stored function to extract hexadecimal MongoDb _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... for(var i=0;i<doc.length;i++){
... myArr.push(doc[i]._id.valueOf());
... }
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


Mongodb compare Objectid to String



> typeof db.cars.findOne().toString();
string
>


How to get value of the ObjectId() in MongoDB using JavaScript substring

In this example we will see how to use JavaScript substring method in MongoDB Stored function to extract hexadecimal MongoDB _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().substring(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal MongoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().substring(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using JavaScript slice

In this example we will see how to use JavaScript slice method in MongoDB Stored function to extract hexadecimal MongoDb _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().slice(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().slice(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get typeof the ObjectId() in MongoDB using JavaScript

Getting the typeof ObjectId()


> typeof db.cars.findOne()._id;
object
>


How to get the typeof function variable stored in system.js



> typeof db.eval("return getObjectID()");
WARNING: db.eval is deprecated
object
>

How to get the typeof output value



> typeof db.eval("return getObjectID()")[0];
WARNING: db.eval is deprecated
string
>


Related Topics


Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello Programmers! Welcome to brand new episode of HTML, CSS and JavaScript ‘How To’ series on progrramers. This post will explain ‘How to create horizontal tab window in html using JavaScript and CSS’. I am not a big fan of Bootstrap and jQuery therefore I’ll create the Horizontal Tabs with navigation bar using pure CSS and JavaScript.

First of all, you can click on Try yourself button in below example and check what are we going to create and after that you will find all the require source code of this project. You can also bookmark the repository of progrramers GitHub community where you can find and download the source code of other projects.
If you like our posts please give thumbs up  πŸ‘ on our Facebook page and also share with your near n dears.



How to create horizontal tab window in html using pure JavaScript and CSS :

<div class="navbar">
        <ul>
            <li><a href="#" tab-name="tab-1" class="tab-link">Tab-1</a></li>
            <li><a href="#" tab-name="tab-2" class="tab-link">Tab-2</a></li>
            <li><a href="#" tab-name="tab-3" class="tab-link">Tab-3</a></li>
            <li><a href="#" tab-name="tab-4" class="tab-link">Tab-4</a></li>
            <li><a href="#" tab-name="tab-5" class="tab-link">Tab-5</a></li>
        </ul>
    </div>
    <div class="tab-content">
        <div class="tab tab-1"></div>
        <div class="tab tab-2 hide"></div>
        <div class="tab tab-3 hide"></div>
        <div class="tab tab-4 hide"></div>
        <div class="tab tab-5 hide"></div>
    </div>
Try Yourself



So let’s start

HTML Explanation

Below is the HTML code that has to be defined in your code that create the DOM of navbar links and the blocks of contents (tab elements). When the links are click then only adjacent <DIV>  will display on browser and all other DIVs will be remain hidden. Please create an HTML file named ‘index.html’ and paste the below codes into it and save.

HTML Codes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>How to create tab window in html using JavaScript and CSS – progrramers</title>
    <style>
       /*-----Paste CSS Code Here----------*/
    </style>
</head>
<body>
    <div class="header">
        <h1>How to create tab window in html using JavaScript and CSS – progrramers</h1>
    </div>
    <div class="navbar">
        <ul>
            <li><a href="#" tab-name="tab-1" class="tab-link">Tab-1</a></li>
            <li><a href="#" tab-name="tab-2" class="tab-link">Tab-2</a></li>
            <li><a href="#" tab-name="tab-3" class="tab-link">Tab-3</a></li>
            <li><a href="#" tab-name="tab-4" class="tab-link">Tab-4</a></li>
            <li><a href="#" tab-name="tab-5" class="tab-link">Tab-5</a></li>
        </ul>
    </div>
    <div class="tab-content">
        </div>
        <div class="tab tab-2 hide"></div>
        <div class="tab tab-3 hide"></div>
        <div class="tab tab-4 hide"></div>
        <div class="tab tab-5 hide"></div>
    </div>
    <script>
      //JavaScript Codes Goes Here
    </script>
</body>
</html>

CSS Explanation

CSS will draw every elements as you desire. These codes should be placed between style tags into the head section.

CSS Codes

       *{box-sizing:border-box}
        body{margin:0;padding: 0;font-family: Verdana, sans-serif}
        /*---Navbar CSS Starts----*/
        .header{background-color: #fafafa;color:#434343}
        .header h1{margin:0;padding: 0;}
        .navbar{background-color: #0056c7;}
        .navbar ul{margin:0;list-style-type: none;overflow: hidden;}
        .navbar ul li{float:left}
        .navbar a{color:#ffffff;text-decoration: none;display:inline-block;padding:14px 18px;transition: all .3s ease-in-out}
        .navbar a:hover{background-color: #ffffff;color:#0056c7}
        /*---Navbar CSS Ends----*/

        .tab-content{min-height:380px;border:5px solid #0056c7;border-top:0;position: relative;overflow: auto;}
        .tab-content div{margin-left:53px;min-height: 380px;position: absolute}
        .hide{display: none;}

.hide class is predefined CSS class to hide the elements dynamically

JavaScript Explanation

JavaScript code will fire the functions to hide and unhide the content-tabs when you click on navbar links. Here one thing also is to be mark that don’t get confused with ‘$’ it not a jQuery function variable. This is self defined function which is stored in ‘$’ variable which target the HTML elements using the CSS kind of selector.

JavaScript Codes

var $ = function(_){return document.querySelectorAll(_)}; //donot confuse, this is not jQuery...
            for(var i=0;i<$('.tab-link').length;i++){
                $('.tab-link')[i].onclick = function(){
                //    alert(this.getAttribute("tab-name"));
                    $('.tab-content>.tab').forEach(element => {
                        element.classList.add("hide");
                    });
                    $('.'+this.getAttribute("tab-name"))[0].classList.remove('hide');
                }
            }


Code Explanation


$ = function(_){return document.querySelectorAll(_)}; This function expression is defined the '$' varialbe which is used to target HTML DOMs.

for(var i=0;i<$('.tab-link').length;i++) loop query the length(count) of navbar links '.tab-link' and set the event function on it by looping itself on load.

forEach function loops the content <DIV> elements add the '.hide' class on each '<div class="tab tab-1">' So that every <DIV> elements become invisible.

$('.'+this.getAttribute("tab-name"))[0].classList.remove('hide'); this code fetch the value from tab-name attribute which is becomes a class selector of <DIV> elements and finally which class is matched that <DIV> become visible.

Hoping this post will usefull for you guys. Keep following progrramers : a web school and get latest updates. 
Related Topics

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello Programmers! This post will elaborate how to create ‘min’ and ‘max’ date restriction to HTML DOM Input type date. Today every small and large company requires web applications to maintain their Customers, Products and Accounts etc. These types of application generally include date restriction.



Suppose you have a product warranty management system and the product comes with 15 months warranty from date of product manufacture and 12 months from date of product sale. To maintain the warranty on that product you have to specify min and max warranty date criteria on the product management application.

This post will show you step by step that ‘How to create HTML DOM Input type date ‘min’ and ‘max’ restriction using JavaScript?

Look at the below given example :


Simple example of date restriction in HTML Input type date :

<input type="date" id="date" value="2019-08-21" min="2019-08-21" max="2019-08-28" />
Try Yourself



Above example is a simple html code which describe how min and max attribute is use to create the date restriction. This code specified here to understand that how the date restrictions work.
Now you go through another example given below this example explains How to set min attribute value to restrict past date using JavaScript in the beginner mode.

Dynemic minimum date restriction using JavaScript :

var n = new Date(); //date constructor
var y = n.getFullYear(); //current full year
var m = n.getMonth()+1;  //current month
var d = n.getDate();     //current day
//padStart fix length of sting as per requirement, for e.g. when month = 8 then month become 08
var today = y.toString().padStart(4, 0)+"-"+m.toString().padStart(2, 0)+"-"+d.toString().padStart(2, 0); //current date
var elem = document.getElementById("date"); //HTML DOM input type date
function restric(e){
    e.value = today;
    e.setAttribute("min",today);
}
restric(elem); //function called
Try Yourself


Above example sets only min attribute while another example given below sets both min and max attribute using JavaScript function. This example creates two variable ‘today’ and ‘maxday’ that provides the value for min and max attribute respectively.

Dynemic minimum date restriction using JavaScript :

//get today
var n = new Date();
var y = n.getFullYear();
var m = n.getMonth()+1;
var d = n.getDate();
var today = y.toString().padStart(4, 0)+"-"+m.toString().padStart(2, 0)+"-"+d.toString().padStart(2, 0);
//get max day
var days = 7; //change the number of day that how many maximum days you want to restrict
var m = new Date(n.getTime() + (days * 24 * 60 * 60 * 1000));
var ymax = m.getFullYear();
var mmax = m.getMonth()+1;;
var dmax = m.getDate();
var maxday =  ymax.toString().padStart(4, 0)+"-"+mmax.toString().padStart(2, 0)+"-"+dmax.toString().padStart(2, 0);
var elem = document.getElementById("date"); 

function restric(e){
    e.value = today;
    e.setAttribute("min",today);
    e.setAttribute("max",maxday);
}restric(elem);
Try Yourself


Also check the below example where min, max and current date is returned through a function called mydate(e) where ‘e’ is parameter referred as number of days. For e.g. if you want min date 7 days before and max date 7 days after from current then you simply set setAttribute(‘min’, mydate(-7)) and setAttribute(‘max’, mydate(7)) while calling JavaScript function restrict().

Dynemic minimum date restriction using JavaScript :

//don't confuse it is not jQuery:
var $ = function(_){return document.querySelectorAll(_)};
function myDate(e){
    var n = new Date();
    var t = new Date(n.getTime() + (e * 24 * 60 * 60 * 1000)); //get time in milisecond
    var y = t.getFullYear();
    var m = t.getMonth()+1;;
    var d = t.getDate();
    var date =  y.toString().padStart(4, 0)+"-"+m.toString().padStart(2, 0)+"-"+d.toString().padStart(2, 0);
    return date;
}
function restric(){
    $("#date")[0].setAttribute("min",myDate(-7));
    $("#date")[0].setAttribute("value",myDate(0));
    $("#date")[0].setAttribute("max",myDate(7));
}restric();
Try Yourself


Pro example with explanation 

Finally coming on conclusion of this post let’s check one last example where date is returned through a function similarly above example, ‘r’ is an object which can suppose to be a server response which contains min, max and current date values. restric() function loops though ‘r’ object and set the min, max and current values to HTML DOM input.

Dynemic minimum and maximum date restriction using JavaScript - pro version coding

//don't confuse it is not jQuery:
var $$ = function(_){return document.querySelectorAll(_)};
/* 'r' object can be parse as server response, for e.g. : e-commerce site maintain warranty one year from date of products sale.
minium and maximun can be set as product warranty period from date of sale*/
var r = [{name:"min", value:myDate(-3)},{name:"value",value:myDate(0)},{name:"max",value:myDate(3)}];
function myDate(e){
    var n = new Date();
    var t = new Date(n.getTime() + (e * 24 * 60 * 60 * 1000));  //get time in milisecond
    var y = t.getFullYear();
    var m = t.getMonth()+1;;
    var d = t.getDate();
    var date =  y.toString().padStart(4, 0)+"-"+m.toString().padStart(2, 0)+"-"+d.toString().padStart(2, 0);
    return date;
} 
//creating a function to set Attribute to HTML DOM input   
function restric(){
    //forEach loop for sertting attribute min, value and max value on HTML DOM input
    r.forEach(function(key) {
        //target the DOM with QuerySeletorAll using DOM 'id'.
        $$('#date')[0].setAttribute(key.name, key.value);
    });
}restric(); //calling restric function on load
//when HTML DOM get changed then function will be fire it conditions hmatched.
$$('#date')[0].onchange = function(){
    if(this.value < r[0].value || this.value > r[2].value){
        this.value=r[1].value;
        alert("This is invalid date selection. Please select the date between "+ r[0].value + " to "+ r[2].value);
    }else{
        if(this.getAttribute("min")==undefined ||this.getAttribute("min")==undefined){
            alert("Correct Date Selected");
        }
    }
}
Try Yourself


onchange  EventListener function expression declared for security purpose if someone delete the min and max attributes from element inspect module then this function expression will restrict the users to make invalid log in.

Hoping this post will clear the whole concept of date restriction. If there is any problem then please write down in the comments and share your problem with us, It’ll will a pleasure to help you.
Related Topics

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello Programmers! This JavaScript tutorial will elaborate "How to get JavaScript Date in input type='date' element?".

Sometimes beginners programmers face this general problem while creating dynamic web applications. When we try to fetch JavaScript Date value in HTML DOM <input type="date"> it doesn't set the date.

Set a date value for date field:

document.getElementByID("demo_date").value = "2019-08-20";
Try Yourself

Above example return the result




In the above example a date string is set to HTML input type=”date” value very easily but when working with JavaScript date constructor ‘new Date()’, it create problems. We have various solutions for this problem. You can try this one :

Set a date value for date field:

today = year.toString().padStart(4, '0')+'-'+month.toString().padStart(2, '0')+'-'+day.toString().padStart(2, '0');
Try Yourself

Another solution using 'toISOString()' method.
In below given example we have used JavaScript toISOString() method with a little trick. toISOString() method returns the International Standard time. Local-time may be different from other time standard. To rectify this problem we have find the time difference between UTC and local-time using 'getTimezoneOffset()' method, converted into milliseconds and added to the local-time. After that we have converted the time to ISOString() and extracted the date using substr(0, 10) method.

Set a date value for date field:

var d = new Date().getTimezoneOffset();
var date = new Date(new Date().getTime() - d * 60 * 1000);
document.querySelector('[name=date]').value=date.toISOString().substr(0, 10); 

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello World! I am here once again with continuation of my previous post ‘How to Create Animated Registration Form Using HTML, CSS & JavaScript’. In previous post we have see an Animated User Registration Form which was built using HTML, CSS & JavaScript.

If you have not read yet please click this link to go through:


Progrramer Tutoials : Animated User Registration From with Validation Design
How to create Animated User Registration From with Validation using HTML, CSS and JavaScript


This form was basically designed for beginners but now it’s gonna be little tricky with few complex JavaScript codes. I would suggest observing the codes very carefully and if there is any issue with the concept please feel free to ask me by writing your problems in to the comments.

Okey in this article we will create same User Registration Form more advance and able to restrict invalid or empty value entry from user side. But before we go ahead first we must understood the importance of Restriction of invalid entry from client side.

Generally restriction of invalid entry through any kind of form is known as ‘Validation’ or ‘Form input validation’. Validation is a process that checks and controls the form input data. For example say you have a registration form where visitor/user feed first name, last name, email and password to create their account on you website. If you want that every user must feed their email address and password in proper manner then they must go through a validation process which checks and returns that submitted data is correct and well structured or not.

If you want to check our live example please clicks the below link.





Be careful: Client side validation is just like a guide for the user/visitors. Client side validation only filters the input data as you want but it can be manipulated by the experts. You must validate the inputs with server side validation process also. Server validation post will uploaded soon be with us and let’s move to logical explanation of this registration form.

Logical Explanation



The logic working behind this Registration Form is little complex. Every adjacent label of text input field which has required attribute get added  ‘**’ on ending of word as suffix by invoking function ‘addph()’ on load.

Progrramer Tutoials: Animated_User_Registration_Form_Required_Field


Whenever user focus on the input fields then myfocus() function will fired on ‘onfocus event’ and the adjacent label will float upside but when user loose the focus from input field JavaScript function ‘myblur()’ will be fired on ‘onblur event’ and the function will check whether the input field has required attribute or not. If it has required attribute then it will throw the animated error ‘This is required field’ else the label move back to its previous position.

When user once again focus on same field error will be disappeared by re-calling myfocus() function.
Whenever user type something the input field then mytxt() function will be call on ‘onkeyup event’ and it will show a clear text button on the right side of the same text input field. If user want to delete the input users do not have press delete or backspace key for long time, he just need to click clear text button and text field will be empty.

Progrramer Tutoials: Animated_User_Registration_Form_Mouse_Pointer


Here are the HTML codes. Copy and paste into your favorite editor and save as index.html file.



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content ="HTML, CSS, JaavScript, Animated Registration Forms">
<meta name="description" content ="How to create Animated Registration Form Using HTML, CSS & JaavScript">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<title>Animated User Registration Form with Validation - Progrramers Tutorials</title>
<style>
//CSS Code goes here
</style>
</head>
<body>
<h1>Sign Up Form</h1>
<div class="container">
<div class="myform">
<div class="mylogo">
<i class="fas fa-user"></i>
</div>
<div class="myinput">
<div class="mylabel txt_trans"></div>
<div class="mytext"><input type="text" placeholder="User Name" class="txt_input" required></div>
<span class="cleartxt"><i class="fas fa-window-close"></i></span>
<span class="errortxt"></span> 
</div>
</div>
<div class="myform">
<div class="mylogo">
<i class="fas fa-envelope"></i>
</div>
<div class="myinput">
<div class="mylabel txt_trans"></div>
<div class="mytext"><input type="email" placeholder="Email" class="txt_input" required></div>
<span class="cleartxt"><i class="fas fa-window-close"></i></span>
<span class="errortxt"></span> 
</div>
</div>
<div class="myform">
<div class="mylogo">
<i class="fas fa-key"></i>
</div>
<div class="myinput">
<div class="mylabel txt_trans"></div>
<div class="mytext"><input type="password" placeholder="Password" class="txt_input" required></div>
<span class="cleartxt"><i class="fas fa-window-close"></i></span>
<span class="errortxt"></span> 
</div>
</div>
<div class="myform">
<div class="mylogo">
<i class="fas fa-check"></i>
</div>
<div class="myinput">
<div class="mylabel txt_trans"></div>
<div class="mytext"><input type="password" placeholder="Confirm Password" class="txt_input" required></div>
<span class="cleartxt"><i class="fas fa-window-close"></i></span>
<span class="errortxt"></span> 
</div>
</div>
<div class="myform">
<div class="mylogo">
<i class="fas fa-globe"></i>
</div>
<div class="myinput">
<div class="mylabel txt_trans"></div>
<div class="mytext"><input type="url" placeholder="Website" class="txt_input"></div>
<span class="cleartxt"><i class="fas fa-window-close"></i></span>
<span class="errortxt"></span> 
</div>
</div>
<div class="myform">
<div class="mylogo">                
</div>
<div class="myinput">
<div class="mylabel txt_trans"></div>
<div class="mytext"><input type="button" value="Save" class="txt_button"></div>
</div>
</div>
</div>
<script>
//JavaScipt code goes here
</script>
</body>
</html>





These are the CSS codes which will stylize you HTML tags on browser. Copy and paste into the head tags of index.html file that you recently created. Save it like show in the image.



*{box-sizing: border-box}
body{background: #244e63;font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}/*Change the color of body*/
h1{text-align: center;color:#FFF;}
.myform{height:48px;display: flex;margin:20px;}
.mylogo{width:48px;font-size:24px;display: flex;flex-direction:column;justify-content:flex-end;text-align: center;color:#FFF;}/*--Change the color of logo--*/
.myinput{width:calc(100% - 50px);position: relative;}
.mylabel{position: absolute;left: 0;right: 0;top: 0;bottom: 0;font-size:14px;transition:all 0.3s;color:#edff47} /*--Change the color and transition of label --*/
.mytext{position: absolute;left: 0;bottom: 0;right:4px}
.txt_input{width: 100%;height:25px;outline: none;border: none;border-bottom: 1px solid #aaa;background: transparent;font-size: 16px;color:#FFF}
.txt_trans{font-size:16px;padding-top:22px;color:#999} /*--Change the landing color after transition of label --*/
.txt_button{background:#0099FF;padding:10px 30px;outline:none;border:none;border-radius:5px;color:#fff;font-size:18px;transition:all 0.4s}
.txt_button:hover{background:#ff9900;color:#212121}

/*Error Part*/
.errortxt{position: absolute;bottom: -16px;left:250px;font-size:14px;color: #ff9900;transition:all 0.2s;visibility: hidden;}
.cleartxt{position: absolute;bottom:0;right:250px;color: #ff9900; font-size:14px;cursor: pointer;transition:all 0.2s;visibility: hidden;}
.showcleartxt{visibility: visible !important;right:10px;}
.showerrortxt{visibility: visible !important;left:0px;}



At last but the most important one, the JavaScript. Copy and paste the JavaScript code in the script tags located at bottom part of index.html file. Save it like show in the image.



var _ = function($){return document.querySelectorAll($)};
            const elem = _(".txt_input");
            window.onload = function(){
                addph(elem);
            }
            //add placehoder function
            var addph = function(e){
                for(var i=0;i<e.length;i++){
                    e[i].parentNode.parentNode.querySelector(".mylabel").innerHTML = e[i].getAttribute("placeholder");
                    e[i].setAttribute("placeholder", "");                
                    if(e[i].hasAttribute("required")==true){
                        e[i].parentNode.parentNode.querySelector(".mylabel").innerHTML += " **";
                    }
                }
            }
            //for loop start
            for(var i=0;i<elem.length;i++){
                elem[i].onfocus = function(){
                    myfocus(this)
                }
                elem[i].onblur = function(){
                    myblur(this);
                }
                /*script for clear text button*/
                elem[i].onkeyup = function(){
                    mytxt(this);
                }
            }
            //for loop end
            //for loop start        
            /*script for clear text button*/
            for(var i=0;i<_(".cleartxt").length;i++){
                _(".cleartxt")[i].onclick = function(){
                    cleartxt(this);
                }
            }
            //for loop end

            //myfocus function
            var myfocus = function(e){
                e.parentNode.parentNode.querySelector(".mylabel").classList.remove("txt_trans");
                e.parentNode.parentNode.querySelector(".errortxt").classList.remove("showerrortxt");
                e.parentNode.parentNode.querySelector(".errortxt").innerHTML = "";
            }
            //myblur function
            var myblur = function(e){
                if(e.hasAttribute("required")==false){
                    if(e.value === ""){
                        e.parentNode.parentNode.querySelector(".mylabel").classList.add("txt_trans"); 
                    }                   
                }else{
                    if(e.value === ""){
                        e.parentNode.parentNode.querySelector(".errortxt").classList.add("showerrortxt");
                        e.parentNode.parentNode.querySelector(".errortxt").innerHTML = "This is required field";
                    }
                }
            }

            var mytxt = function(e){
                var cleartxt = e.parentNode.parentNode.querySelector(".cleartxt");
                if(e.value == "" || e.value == null || e.value == undefined){
                    cleartxt.classList.remove("showcleartxt");
                }else{
                    cleartxt.classList.add("showcleartxt");
                }
            }

            var cleartxt = function(e){
                var txt_input = e.parentNode.querySelector(".txt_input");
                txt_input.value = "";
                txt_input.focus();
                e.classList.remove("showcleartxt");
            }
            

            _(".txt_button")[0].onclick = function(){
                alert("You have click save button");
            }



Save and run the index.html file into your favorite browser. What you are observing please write in to the comment section we will wait for your comments. You can also ask for custom code snippets.

Follow our blog by registering you email on our blog, trust us we will never spam you, also like us on our Facebook page.

Next post will elaborate how to work with regular expression and error handlers to prevent the unwanted entry on the same form which we have created today. Thanks for joining us have nice day.

Related Topics