Checkbox Validation In Javascript 2021

Checkbox validation in javascript
Table of Contents

Want to know how to checkbox validation in javascript you have added a checkbox in your project and now you don’t know how to do validate it don’t worry today I will tell you how to do Checkbox validation in Javascript.

Checkbox is a HTML input which defines square box which allows users to make a selection by clicking the checkbox. Here are some more tutorials on Javascript validation.

Checkbox Validation In Javascript

Now lets see how to do checkbox validation in javascript it is very simple to do I will show you step by step how to do it. this is what we will archieve:

  • Check if checkbox is selected.
  • Show a error message if checkbox not checked.

Create A HTML Checkbox

First you need to create a form and inside the form add a checkbox html input and add a button inside it give id’s to the form and input like this:

				
					  <form id="form">
        <input type="checkbox" id="checkbox">
        <button type="submit">Submit</button>
        <h5 id="message"></h5>
    </form>
				
			

Add Javascript Code

Now add the below javascript code in your file or script tag add the name of your id properly this code will check if the user has selected the checkbox or not.

				
					const form = document.getElementById('form')
const checkbox = document.getElementById('checkbox')
const message = document.getElementById('message')

form.addEventListener('submit', function validateCheckbox(e) {
    e.preventDefault()
    if (checkbox.checked === true) {
        message.innerHTML = 'Done'
    }
    else {
        message.innerHTML = 'Please check something'
    }
})
				
			

This was it checkbox validation in Javascript I hope you found this useful and helpful if you want a video tutorial you can watch this video.

If you want more tutorials like this do subscribe to our newsletter or join our Telegram channel here – JOIN TELEGRAM CHANNEL for future blog updates.

Thank you for reading, Have a nice day 🙂

Share This Post
Share on facebook
Share on twitter
Share on email
Share on whatsapp

Leave a Reply

Subscribe To Our Newsletter

Get updates and learn from the best

Latest Guides & Articles