Design custom form in CSS, JavaScript and PHP tutorial Pt2

Table of Contents

Today we will continue in the Design custom form in CSS, JavaScript and PHP tutorial we started a day ago. For first part we already have the HTML and CSS in place and ready so today we can focus solely on JavaScript side of the project. Since we will work on JavaScript part of the project, we are going to use the same resources as before except the font CDN. So, without further ado let’s continue in the project …
Resources:

Modernizr:

http://modernizr.com/

Codepen live demo:

https://codepen.io/d3v3r0/pen/jcxbL

GitHub repository:

https://github.com/d3v3r0/Custom-form-in-CSS-JavaScript-and-PHP

Even though forms are enhanced in great way in HTML5 spec, these features are useless when users are using browsers which does not support them. For this reason, we will create a JavaScript based backup plan to make sure the form is behaving exactly like we want. To get the job done properly we will use Modernizr library to detect supported and unsupported features and to create JavaScript fallbacks for them. It is important to note that no matter how hard you try, and how many lines of code you write, if some user will use outdated browser and block JavaScript, all we did is useless. This is reality. There will always be some cases where you cannot control all possibilities. So, let’s start.

JavaScript

The first thing is we will do is to create new function which will be loaded right after loading the page (i.e. form). This requires selecting “window” object and using “onload” event and assigning new function to it. This function will take no arguments. As said onload along with window will ensure running all the code inside the function to run automatically when page (window) is loaded.

JavaScript:

window.onload = function() {}

From now on, we will work inside this function and so all the code will be written inside the curly brackets. Every single Modernizr test will be created by using if statement. First feature we will bulletproof is autofocus. In HTML we used “autofocus” attribute on the first input for name. Let’s create new if statement. The condition will be “Modernizr.input.autofocus” preceeded by exclamation mark. This line means that Modernizr library will be started and it will check if “autofocus” attribute for input elements is supported in the browser. Normally, the condition would return “true” for support and “false” otherwise. By using exclamation mark “true” will be returned every time when “autofocus” is not supported.

JavaScript:

if (!Modernizr.input.autofocus) {}

Inside this statement (inside curly brackets) we will create new variable called “inputs” and use “document” object with “getElementsByTagName()” method with “input” as parameter to cycle through the whole document (page) and store all the input elements inside it. This variable will become array containing three input elements (name, mail, number). To select the first of them we will use name of the variable followed by square brackets containing “0”. Remember, in programming, first item in array is on index number “0”. Then, we will use “focus()” method on this element. With this, focus is done.

JavaScript:

if (!Modernizr.input.autofocus) {
 var inputs = document.getElementsByTagName('inputs');
 inputs[0].focus();
}

Next thing is to hide label elements on browsers supporting “placeholder” attribute. Let’s create new if statement with “Modernizr.input.placeholder”. now without exclamation mark because we want to work with case when placeholder is supported. For this case, let’s create new variable called “labels” and, again, use the “document” with “getElementsByTagName()” method with “labels” as parameter to collect and store all the labels in the form inside this variable. Now we are going to use “for” loop to cycle through the “labels” array and add “js-hidden” (in Pt1 it was called hidden) class to every item (label). First part of loop – initialization – will compose of two variables “i” and “j”. “i” will be set to “0” and “j” to “labels.length”. Second part – the condition – will be “i < j”. The last part – the increment – will be “i++”. To summarize it … Loop will start on “0” (i = 0), increment by one (i++) and it will run until it will reach the end of array (i < j).

For every cycle we will select each item by using variable name “labels” with square brackets containing “i” (number which will increment with each cycle) and use “classList” with “add()” method and “js-hidden” as parameter. After this, when browser is supporting “placeholder” attribute labels will be hidden.

JavaScript:

if (Modernizr.input.placeholder) {
 var labels = document.getElementsByTagName('label');
 for (var i = 0, j = labels.length; i < j; i++) {
  labels[i].classList.add('js-hidden');
 }
}

Now we are going to create fallback for “required” attribute. It means stopping the form from being submitted if any of required fields (name, phoe or mail) is blank. For this let’s create another if statement with “!Modernizr.input.required” as condition. Inside the statement will be four variables – form, name, mail and phone. All of them will use “document” object and “getElementById()” method with id of every element as parameter to associate the element with variable. On next line we will create new if statement that will use variable names with “value” property to check for length of their values if it is lower than “1”. In true cases it will select the form via “form” variable, use “onsubmit” event and function with no parameter. This function will return “false” – prevent form from being submitted.

JavaScript:

if (!Modernizr.input.required) {
 var form = document.getElementById('js-form');
 var name = document.getElementById('js-name');
 var mail = document.getElementById('js-email');
 var phone = document.getElementById('js-tel');
 if (name.value.length < 1 || mail.value.length < 1 || phone.value.length < 1) {
  form.onsubmit = function() {
   return false;
  });
 }
}

However, even though it would be funny, we have to create JavaScript code for checking the inputs every time when something is changed to allow user submit the form if all required fields are filled. Right under the if statement select the “form” variable with “onchange” event and assign new function to it. Inside this function will be if statement that will check if all the fields are filled. To get this done, let’s use the variable names for individual input fields with “value” and “length” property and check if it is higher than “1”. In true situation, again, select form via “form” variable and use “onsubmit” event and assign it to new fuction. Now this function will return true – form will be submitted.

JavaScript:

form.onchange = function() {
 if (name.value.length > 1 && mail.value.length > 1 && phone.value.length > 1) {
  form.onsubmit = function() {
   return true;
  };
 }
}

To make it more digestible let’s end it up here for today. In next part we will focus on indidual input fields and use regexp to check for valid values.

Summary

We successfuly made couple features bulletproof by providing additional JavaScript fallbacks. Now we are no longer dependent on support for placeholder, focus or required attributes. In next part we will deal with input fields and make sure the form will be submitted only with valid values. See ya soon.

If you liked this article, please subscribe so you don't miss any future post.

If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂

By Alex Devero

I'm Founder/CEO of DEVERO Corporation. Entrepreneur, designer, developer. My mission and MTP is to accelerate the development of humankind through technology.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.