How to handle HTML checkbox events

The HTML checkbox input element allows you to select a single value for submission in a form for example if you are creating a form and want to know if the applicant is fluent in English or not you can have a checkbox and if the user thinks he/she is fluent in English he/she checks it if not leaves it unchecked .

In this tutorial we are going to learn

  1. How to handle onclick and onchange events and the difference between them
  2. How to handle checkbox events in Jquery
  3. How to submit a form when checkbox is clicked
  4. Show/ Hide a section of the form when checkbox is clicked

To start working with checkboxes we will create a form that contains a checkbox , in this example we will be building a form that takes the a user name and has also a checkbox that the user should check if he thinks he is fluent in English , if not a prompt will appear showing the user a text that says you need to be fluent in English to apply for the job.

Checkbox event handling using pure Javascript


Now what we need to do is to attach an event to the checkbox so it checks it’s state each time it’s changed and show the message if it has been unchecked , notice I added a checked property to the checkbox so it is checked by default.

There are two events that you can attach to the checkbox to be fired once the checkbox value has been changed they are the onclick and the onchange events.

There is a problem with the onchange event is that it is not called until the checked state has been updated and since Internet Explorer does not fire the onChange event till the checkbox loses focus so it will create different results than in Google chrome and other browsers so to avoid all this I recommend you stick to the onclick event.

Here I added an on click event and make it so it will call a function called checkFluency() once it is clicked

Here in the checkFluency() function , picked the checkbox and then if it is not checked an alert is shown saying “you need to be fluent in English to apply for the job”

Using jQuery


We could have done the same thing using jQuery and in fact that is what we are going to be doing next .
jQuery is the most famous JS library ever created , and a lot of people use it daily as it makes their job a lot easier . You do not need to worry if you do not know jQuery , it’s concepts are very easy and I will be explaining everything as we go along.

I only added jQuery and couple of CSS lines to style our page.
I also added the same exact HTML code we used in the previous code , the only difference will be in our javascript code since in this example we will be using jQuery instead of plain javascript.

You may notice that the only thing I changed from the previous example is that I have deleted the onclick event in the checkbox which makes sense , since in jquery we will be attaching the event to the element no need to call it from the HTML code.

Now to the javascript code where all the magic happens :

If this seems overwhelming to you , no need to worry , I will be explaining everything in details. First, I am using the $(document).ready(); that I have told you about and inside it I added an anonymous function.

If you are not familiar with anonymous functions they are functions that are declared in runtime and the reason they are called anonymous is that you create them without giving them a name.

And inside the anonymous function I placed the following code :

First, we are using the dollar sign ‘$’ which is a shorthand for jQuery so this $(‘#fluency’) is the same exact thing as jQuery(‘#fluency’). Then we are attaching to it an on change event and inside it we are using the anonymous function syntax for the second time. The code that is inside the anonymous function will be run each time the event is fired.

This is the same exact if statement we used in the first example with only a very small change , which is instead of getting the checkboc using document.getElementById() we are using the “this” keyword.
If you are not familiar with the ‘this’ keyword , here in this example it refers to the target that fired that event which is here the checkbox we want to grab.

Submitting the form when checkbox is clicked

Sometimes you might want to submit the form just when the user clicks a checkbox, rather than making the user press the submit button.

All what we will have to do is give an id to the form , I gave it an id of myform, then use jQuery to grab and submit the form.

Hide/show elements when checkbox is selected


I am sure most of you have seen a lot on the Internet which is when there is something hidden in the form , something like a section for extra information or feedback and you press on a checkbox to toggle it and show it or hide it . And this is what we will be building. We are going to be using jQuery because it will be much easier and shorter and I do not want you to get lost in a lot of lines but this example can be done with only javascript and it will not be hard .

In the code above we have a div and inside it we have a form that contains a text with a placeholder text of name which will contain the name of the applicant , another input with type e-mail , checkbox and a text area .
When the checkbox is checked the textarea should appear so by default it should be hidden.
So we make the container div (with id conditional_part) hidden

Next step is creating the javascript which is going to make this textarea appear and disappear .

The javascript for this example is pretty straight forward :

Here, we are first grabbing the checkbox which we gave an id of more-info and attaching to it an onchange event that fires an anonymous function when the event is fired.

Inside this anonymous function we are having the same if statement we used in the previous example to check whether the checkbox is checked or not. And inside them we are using the jquery hide() and show() functions . These functions simply change the display type of the div (with id ‘conditional_part’) .

HTML input type password field – example code and techniques

The HTML <input type=”password”> element is a specific type of input elements used to create input fields that deal with passwords . It is designed to deal with passwords so it’s more secure than the normal <input type=’text’> we see in every form on the internet.

First: It makes the password not visible to anybody sitting around you by showing “.” or “*” instead of the characters you type.

Second: Browsers treat inputs with text type and password types differently , browsers may try to automatically refill the text input types if they have been previously entered which is something you may not always want.

HTML <input type=”password”> element is where you should make the user type their password in , and in this article we will know how we can customize the password input fields to accommodate our needs.

By the end of this tutorial you will know how to

  1. create a password input field and style it
  2. add a button that can enable the user to view his password in plain text
  3. add validation to your password input field
  4. create a numbers only password field

Creating a password input field is as simple as typing <input type=”password”> and it will come packed with every thing we need as hiding the password and replacing it with dots.

Now it’s time to add some logic to our example here , we will create an eye icon that you can click to show
the password and click again to hide it.

Show/Hide Password Mask


Here all what I have done is created a div that contains the password input field and it has an id of “password-field” which we will use later to give it style and reference it in our javascript file next we created an I element with class “fa fa-eye” and id of “pass-status” which will create an eye icon using fontawesome

Note: if you are not familiar with font awesome do not worry it’s a simple font that contain many icons that are used allover the web as they are very easy to style.

We also added an onClick event to our icon that calls a function called viewPassword each time it is clicked . Here is the final result so far do not worry if yours looked different you can copy all the css from our codepen

Now we need to create the javascript code to check if the password is already hidden view it and change the icon to a crossed eye.

To make this example work we need to check first to see if the password is hidden and view it also change the icon to match the view state. To do all this we will use a small trick , we know that what makes our password hidden is the use of “password” as a type for our input so all what we will have to do is when the icon is clicked we will check if our input had a type of “password” we will change it to type “text” which will lead to showing the password till the user click again on the icon.

Remember all this code is written inside the viewPassword() function. All what we are doing here is using an if statement to check if our password input’s type is “password” then change it to text and change the class of the icon’s class to
“fa fa-eye” which is the class for a slashed eye in font awesome. If the input had already a text type which means the icon has already been clicked we will reverse everything we have done by changing the input type back to password and the icon class name to “fa fa-eye” which will make the password hidden again and will make .

Checking for Password Strength


Enabling the user to show and hide his password is not all that we can do , a study has show that one each fiver users use 123456 as their password which is very unsafe and all the fancy stuff website developers do nowadays from hashing to salting all of this will not make any difference if the hacker can simply guess your password and if you use any in the list of top famous 25 password , there is a pretty good chance the hacker may be able to guess it right. One way we can solve this issue is to add validation to your password input for example force your user to create a password that contain at least one letter , one digit and 8 characters. And this is exactly what we will do now.

Here we did the same as the first example we created a div with a class of “second-example” and added in it a password input with an id of “password-2” and I added an onkeyup event and made it’s value equal to a validate() function .

Note : we used here onkeyup event because onkeydown will fire the event once the key is pressed before even the character is typed on the screen which will lead to a problem causing the password to not be written.

We also added a div with an id of “validation-txt” that will contain all the warning that we will display to the user.

Now we need to create the javascript that will make all this happen. First we create the function validate() that will contain all our code

In the code above we used document.getElementById to grab the password input and the validation div that will contain all our warnings . We also created a variable called content and we assigned it to password.value which is the value of out password input field , we also created an empty array that will contain all our validation errors to be able to view them to the user.

Next we need to start validating the password each time a character is typed and check if it satisfies our validation conditions or not.

As I mentioned before we will check if the password’s length is greater than 8 characters and if it contains at least one litter and one digit.

We will start by the easiest one which is checking that the password is longer than 8 characters

Here, we are using the length property to check if our password has less than 8 characters and if it does we are using the push function to push the string “Your password must be at least 8 characters” to the errors array we created before.

Next we need to check if the password field contains at least one letter , unfortunately there is no native way we can do this easily in javascript so we will have to use regular expression or as sometimes called “regex”. Do not worry if you are not familiar with regular expressions or never heard of them before , regular expression is a special string that describes a search format , we can use it to search for a phone number in a long document by just knowing it’s format 998- 902-142. Here we are going to use it to check once if the password contains at least one letter and if it contains at least one digit.

Here we are using the search function which is a special regular expression function built natively to javascript to check a regular expression term against a string. Here “/[a-z]/i” means that the search function will be searching for any character from a to z and “/[0-9]/i” will search for any digit between 0 and 9 and if it does not wound any it uses the push function we have talked about earlier in this tutorial to add the warning string to the errors array.

The last thing we need to do is to add the errors we collected in our errors array to out html.

Here we are using an if statement to check if the number of elements in the array are greater than zero which means there has been validation errors then we use the join function to attach all the elements of the array together in one string separated by the “,” comma sign then adding our results to the html in the validation div we have created.

“Digits only” Password field using CSS


The last thing we are going to learn about in this tutorial is how to make a password input field that accepts numbers only. This is very useful for example if you are trying to create an input field for a pass code that needs to be only in numbers and want the mobile users to automatically see the number pad once the click on the input field .

This time we will not be creating a password input field , we are going to be creating a numeric input field instead

Here we created an input element with a type of number and added pattern=”[0-9]*” this is supported in safari and most browsers and will make the number pad in the mobile phone pop up automatically once the input field is in focus.

What is remaining now is to hide the password to make it look like other password inputs that we have made and remove the number spinner that appears by default in a lot of browser. Fortunately this is very easy using CSS 3.

In the first part, we are using the id of the input element to hide the password and replace it with the dots like other input field with type of password and the second part we are changing the style of every input element with type number to change the outer and inner spinners that sometimes appear natively in some browsers to enable users to increase and decrease numbers.

How to Create a Telephone Input Field in HTML5

Though  field validation and data formatting are the biggest challenges of working with web browsers, HTML5 does some help in enforcing this for us.

Telephone input field can be created using type=”tel”:

This looks like every other input field, with the difference that it optimizes the keyboard. Certain platforms like tablets, or smartphones will pop-up only-numeric keyboard for this input field.

It is hard to enforce particular regular expression through HTML because of variety of phone number formats used along with differences in country codes, and number separators. It remains the sole responsibility of the developer to implement these checks through JavaScript or other library function.

For example, here is the pattern for common USA phone format:

you can apply this format using the pattern attribute:

This page has some more examples for phone number patterns in different regions

tel input type is currently supported in all major modern browsers. The full numeric keypad makes a great user experience.


How to Use Html5 Input Type Email

Before the advent of HTML5, handling emails addresses required more work to validate the email addresses using Javascript. Well all that is now not necessary with the new HTML5 input type email.

The email input element has been specifically designed to handle and validate email addresses. Depending on the browser, it will alert the user that the entered information is not correct and the form will not submit until the user makes corrections.

Sample Code:

[click to continue…]

How to Add a Label to HTML Radio Button

Radio button allows user to choose only one of the pre-defined options. Each radio button must be accompanied by a label describing the choice it represents.

There are two ways to label radio button elements. One is to enclose the whole <input type=”radio”> tag inside <label > tags:

[click to continue…]

How to Create a “Yes/No” Radio Button

Using radio button to accept Yes/No questions is best because the field accepts only one of the options. It is better than a dropdown because there are only two choices – either of them can be selected by a single click

Here is the code to create a yes/no radio button.

[click to continue…]

How to Customize HTML5 Date Field Date Format

When date input was added by HTML5, many believed that it would offer the users a friendly, interactive and known method of entering a date on a website. However; this new addition has failed to live up to the expectations and the major reason behind it remains the fickle nature of the format of the input given by the user.

Originally, the date input attribute was designed as a form element to pick values through a datepicker. The problem however, lies in the implementation of datepicker which changes from browser to browser. What it essentially means is that as a web designer you must be intending to allow user to pick a date in the format YYYY/MM/DD via datepicker and you designed your HTML validations accordingly, but when the user accesses the webpage through the browser on his system, he might see a completely different sequence of selections depending upon the default date settings in his/her system and the browser used.

Now there is no said rule in HTML5 that would allow the web designers to change the format in which the date element picks values. Therefore, the rigidness of the date element prompted designers to look for other ways to alter the format of the date to be entered by the user.
[click to continue…]

Creating CSS3 Button Hover Effects

The CSS3 “hover” is a pseudo-class that enables you to select and style elements on a web page when the mouse moves over an element. You can use Javascript or CSS style sheets to react to this event depending on your objective. For example:

The CSS code above styles a button with class ‘checkout’. The default color of the button is blue and when the mouse is over the button, the color changes to green.
[click to continue…]

How to Use HTML5 Input Type ‘file’ – With Examples

If you’re developing a nice website like Facebook or Youtube where subscribers share images and videos, or you’re selling premium content like e-books online, you have to provide a way for users to upload content. In this tutorial, I will show you how to add file uploading capability to your web page like a pro.

The W3C HTML Standard defines several <input > types each designed to handle a specific type of data. For file uploading purposes, the HTML input element, aptly a tag named <input type=”file”>, has been provided. How does it work? Let’s dive straight into the tutorial to find out.
[click to continue…]

Form Validation Using Jquery Examples

When you include forms on your website for user input, it is always advisable to perform some validation on the data entered. This not only ensures that your application receives the type of data it can work with, but it also makes for good UX (user experience) as users will be able to be warned of the incorrect input and be given hints of the kind of data that is acceptable.

There are two kinds of validation: client-side and server-side validation. It is recommended that you perform both. Client side validation is usually done with JavaScript and it serves to give the user quick feedback on input errors before a call to the server is made with the data. Server side validation serves as a second line of defence against invalid data. Even if you have set up client side validation, you should always perform server side validation as JavaScript can be bypassed.
[click to continue…]