Javascript check if one checkbox is checked

How to check if checkbox is checked in JavaScript

To check if a checkbox is checked in JavaScript, you can use the checked property of the HTML element. This property sets or returns the checked state of a checkbox.

Let us say that you have the following checkbox input field:

input type="checkbox" id="checkbox"> 

You can use the following code to check if the checkbox is checked or not:

const elem = document.querySelector('#checkbox') if (elem.checked)  console.log(`Checkbox is checked!`) > else  console.log(`Checkbox is not checked.`) > 

We used the querySelector() method to retrieve the checkbox element from DOM using its ID attribute value. Next, we inspected the value of the checked property to decide whether the checkbox was checked or not.

The checked property can also be used to change the checked status of a checkbox programmatically using JavaScript, as shown below:

// Mark checkbox as checked document.querySelector('#checkbox').checked = true // Uncheck checkbox document.querySelector('#checkbox').checked = false 

If you are using jQuery, the is() function can also be used to check if a checkbox is checked or not:

if ($('#checkbox').is(':checked'))  console.log(`Checkbox is checked!`) > else  console.log(`Checkbox is not checked.`) > 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

How to check whether a checkbox is checked in JavaScript?

In this tutorial, we will learn to check whether a checkbox is checked in JavaScript. The checkbox is the input type in the HTML, which works as the selection box. The radio buttons which belong to the same group allow users to select only one value. Still, the checkbox which belongs to the same group allows users to select multiple values.

Also, you have many uses of checkboxes in your mind yourself. The HTML can add a checkbox to the webpage, but to add the behaviour to the checkbox, we must use JavaScript. Programmers can add different behaviours to the checkbox based on whether the checkbox is checked or not.

Here, we will learn to check for the single and multiple checkboxes is selected or not.

Check if a Single Check Box is Selected or not

In this section, we will learn to check whether the checkbox is checked or not. In JavaScript, we can access the checkbox element using id, class, or tag name and apply ‘.checked’ to the element, which returns either true or false based on the checkbox is checked.

Syntax

Users can follow the below syntax to check single checkbox is selected or not.

let checkbox = document.getElementById("checkbox_id"); let checkbox.checked; // it returns Boolean value

Example

In the below example, we have created the checkbox. Also, we have added the event listener to the checkbox. When the user changes the checkbox’s value, the event listener will be invoked. In the event listener, we will check for the checkbox is checked or not. If checkbox is checked, we will show some text to the div otherwise we will make the div empty.

html> head> title>Check whether the Checkbox is checked or not/title> /head> body> h2>Check whether the Checkbox is checked or not using i> .checked attribute /i>/h2> h4>Check the below checkbox to see the text div/h4> input type = "checkbox" id = "checkbox"> div id = "text"> /div> script> let checkbox = document.getElementById("checkbox"); checkbox.addEventListener( "change", () => if ( checkbox.checked ) text.innerHTML = " Check box is checked. "; > else text.innerHTML = ""; > >); /script> /body> /html>

In the above output, users can see that when they check the checkbox, it shows a message “checkbox is checked.” When they uncheck the checkbox, it shows nothing.

Check if Multiple Checkboxes Are Selected or not

It is simple to add the behaviour to a single checkbox. On many websites, you have seen that when you see the popup to accept the terms & conditions, it has multiple checkboxes and when you select all checkboxes, only it enables the accept button.

Here, we will do the same thing. We will create the multiple checkbox and check for all checkbox whether it is checked or not and on the basis of that, we will enable the button.

Syntax

let checkbox = document.getElementsByName( "checkbox" ); let button = document.getElementById( "btn" );
for ( let i = 0; i  checkbox.length; i++ )  checkbox[i].addEventListener( "change", () =>  >); >
button.disabled = false; for ( let i = 0; i  checkbox.length; i++ )  if ( checkbox[i].checked == false ) // if any single checkbox is unchecked, disable the button. button.disabled = true; >

Example

In the example below, we have created the three checkboxes with the same name, which means all belong to the same group. Also, we have created the button in HTML and the accessing button and checkbox using the id and name in JavaScript.

We have added an event listener in all checkboxes. When any checkbox value changes, it will check whether all checkbox is checked or not. If all checkbox is checked, the event listener enables the button. Otherwise, the button remains disabled.

html> head> /head> body> h2>Check whether the Checkbox is checked or not/h2> h4>Check the below all checkboxes to enable the submit button./h4> input type = "checkbox" name = "checkbox"> input type = "checkbox" name = "checkbox"> input type = "checkbox" name = "checkbox"> button id = "btn" disabled> enable button/button> script> // access elements by id and name let checkbox = document.getElementsByName("checkbox"); let button = document.getElementById("btn"); // Initialilly checkbox is disabled for (let i = 0; i checkbox.length; i++) // iterate through every checkbox and add event listner to every checkbox. checkbox[i].addEventListener( "change", () => button.disabled = false; // if all checkbox values is checked then button remains enable, otherwise control goes to the if condition and disables button. for (let i = 0; i checkbox.length; i++) if ( checkbox[i].checked == false ) button.disabled = true; > >); > /script> /body> /html>

In the above output, users can see that when they check all the checkboxes, button will be enable, otherwise button remains disabled.

In this tutorial, we have learned how we can check whether single or multiple checkboxes are selected or not. We have added the different behaviour to the web page according to the checkbox selection value.

Also, users can use the JavaScript libraries such as jQuery, so users need to make less effort to check for multiple checkboxes.

Источник

How to Check if Checkbox is Checked in jQuery and JavaScript

Checkboxes are one of the several types of input fields we use very commonly to allow users to interact with web pages and typically POST data to a backend, by checking any box that applies to a given situation.

As opposed to Radio Buttons (which belong to Radio Groups) — checkboxes belonging to a single group aren’t mutually exclusive so a user can select multiple boxes that apply. You should keep this in mind when checking whether any options are selected.

In this guide, we’ll take a look at how to check if a checkbox is checked in jQuery — a popular library for JavaScript, and Vanilla JavaScript.

element.checked

Let’s start out with a simple Checkbox setup:

h1>Check if Checkbox is Checked h1> p>Have you taken this test before? p> input type="checkbox" id="takenBefore" placeholder="Yes"> label for="takenBefore">Yes label> button id="button"> Check Checkbox button> 

In pure JavaScript — checking if a Checkbox is checked is as easy as accessing the checked field, represented by a boolean:

// Get relevant element checkBox = document.getElementById('takenBefore'); // Check if the element is selected/checked if(checkBox.checked) < // Respond to the result alert("Checkbox checked!"); > 

However, this code will only ever run if you specifically run it. For instance, you could run it when the user submits a form or wishes to proceed to the next page as a validation step. Validation isn’t commonly done this way, and typically delegated to libraries that are more robust. More commonly, you want to react to the checkbox to change something on the page — such as providing other input options.

In these cases, you’ll want to add an event listener to the button, and let it listen to events, such as being clicked. When such an event occurs — you can decide to respond to the event:

checkBox = document.getElementById('takenBefore').addEventListener('click', event => < if(event.target.checked) < alert("Checkbox checked!"); > >); 

In this setup — the code is constantly waiting and listening to events on the element! Now as soon as someone clicks the Checkbox, your alert() method will execute. This time, however, to obtain the checkBox element, we procure it from the event instance, as the target of that event.

When you open the page up in a browser, and click the button, you’ll be greeted with:

$(‘#element’)[0].checked

Note: jQuery is a popular JavaScript library, present in many projects around the world. Due to its light weight and features that expand the scope of JavaScript’s built-in capabilities — it’s become a staple. Not surprisingly — it can be used to check whether a Checkbox is selected or not.

We can use jQuery’s selector syntax instead of pure JavaScript’s to simplify both the selection of the element and the event listener attached to it.

You can import jQuery in your page via a Content Delivery Network (CDN). You can use jQuery’s own CDN for importing the library as well.

script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> script> 

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property:

let isChecked = $('#takenBefore')[0].checked console.log(isChecked); 

Here, we’d be testing if the takenBefore checkbox is checked, by accessing it via jQuery’s selector, and using the innate checked field as before.

Alternatively, you can define a listener that detects a change:

$('#takenBefore').change(function( ) < alert('Checkbox checked!'); >); 

This code is much simpler, but performs in much the same way as the pure JS solution! Clicking the checkbox will trigger an alert as before:

$(‘#element’).is(‘:checked’))

Instead of checking via the built-in checked property — we can offload the logic to the is() method. The is() method is a general method that can be used for many purposes — and returns a true / false based on the comparison criteria. The :checked selector was specifically made for checking whether a radio button or checkbox element had been selected or not.

So, if you combine these together, it’s easy to check whether a checkbox is(‘:checked’) :

let isChecked = $('#takenBefore').is(':checked'); console.log(isChecked); // true (if checked at the time) 

$(‘#element’).prop(«checked»)

In earlier versions of jQuery — attr() was used to access and manipulate fields of elements. In newer versions, the method was replaced with prop() . It can work as a getter/setter for properties of elements, and in our case — as a wrapper for getting the checked property of an element.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

let isChecked = $('#takenBefore').prop('checked'); console.log(isChecked); // true (if checked at the time) 

is() vs prop()?

So, what’s the difference between is() and prop() in this context?

Both methods appear to work in much the same way from our perspective. So, what’s the difference?

is() has a bit more overhead processing and parsing than prop() . Even considering the fact that prop() doesn’t just access the property and does some validation, it’s more performant when it comes to processing a large number of inputs, say, in a loop.

On the other hand — is() always returns a boolean value, whereas prop() just returns the underlying property’s type. You can’t guarantee that something else sneaked in, and your code may fail at runtime if you don’t use prop() properly. is() also semantically indicates the return value — a boolean , which makes it a more readable option.

Conclusion

In this short guide, we’ve taken a look at how to check whether a checkbox is checked with JavaScript and jQuery.

We’ve used the checked property — directly and indirectly, followed by the is() and prop() methods, as well as taken a quick look as to which you could prefer.

Источник

Читайте также:  Меняем цвет шрифта при помощи HTML
Оцените статью