- How to check whether a checkbox is checked in JavaScript?
- Check if a Single Check Box is Selected or not
- Syntax
- Example
- Check if Multiple Checkboxes Are Selected or not
- Syntax
- Example
- Get checkbox status using javascript
- How to check if a checkbox is checked in javascript?
- 6 Answers 6
- Get the value of checked checkbox?
- 16 Answers 16
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.
Get checkbox status using javascript
You need to access the className variable (pure JS) the following assumes your div has an ID of terms_div , that terms_error is the only class you might want on the div , and that you setup your checkbox with onClick=»validateTerms();»
function validateTerms() < var c=document.getElementById('termsCheckbox'); var d=document.getElementById('terms_div'); if (c.checked) < d.className=''; return true; >else < d.className='terms_error'; return false; >>
heh ours are really close. Only caveat on yours is if there happens to be any other classes assigned to the element itll wipe them out.
I make only one change to this code d.className=’terms_error’; otherwise when i double press the submit button another ‘terms_error’ will add. thanks
Good point Sassi, the += should have be = although a double click should get a check/uncheck so className shouldn’t get messed up (appended once, then cleared).
if(document.form.termsCheckbox.checked==true) alert('check box is cheked')
Simply bind an onchange handler to your checkbox.
$("#termsCheckbox").change(function() < // class will be removed if checked="checked" // otherwise will be added $(this).toggleClass("terms_error", !this.checked); >).change(); // set initial state
Live Demo (Click the «Terms Div» text to test)
I didnt see the question tagged with jQuery, but I noticed a jQery selector was used.. so just to be safe I did it with pure JS anyway.
var terms = document.getElementById("termsCheckbox"), terms_div = document.getElementById("terms_div"); function validateTerms() < if(terms.checked == false)< if(terms_div.className.indexOf("terms_error")<0)< terms_div.className += " terms_error"; >return false; >else < terms_div.className = terms_div.className.replace(/\bterms_error\b/,''); return true; >>
How to check if a checkbox is checked in javascript?
I have multiple checkboxes and I would like to know if one of them is checked. My code does not give me any error, but I don’t get the results I am expecting. When I run the code always get the first alert which is inside the for loop. The following is my code:
function validate() < if(document.getElementById('postTW').checked || document.getElementById('postFB') )< var checker = document.getElementsByName('twitter[]'); for (var i = 0; i < checker.length; i++) < if(checker[i].checked)< return true; >else < alert("Not enough arguments "); return false; >>; > else < alert("Not enough arguments to submit the form"); return false; >>
6 Answers 6
This code checks only 1st checkbox because of return:
var checked_flag = false; for (var i = 0; i < checker.length; i++) < if(checker[i].checked) < checked_flag = true; >>; return checked_flag;
Are there logic errors in the following code?
I assume you want something like this:
var flag=false; for (var i = 0; i < checker.length; i++) < if(checker[i].checked)< flag=true; >>; if (!flag)
Use a flag that will return false if any checkbox of name twitter[] is not checked
function validate() < if(document.getElementById('postTW').checked || document.getElementById('postFB').checked )< var result = true; var checker = document.getElementsByName('twitter[]'); for (var i = 0; i < checker.length; i++) < if(!checker[i].checked)< alert("Not enough arguments "); result = false; return; >>; > else < alert("Not enough arguments to submit the form"); result = false; >return result
Looks like you have a logical error in your code. As written, if the first checkbox is not checked, then you will fall through to the else statement and display the alert. You should simply get rid of the first else statement and move the first alert outside of the for-loop:
function validate() < if(document.getElementById('postTW').checked || document.getElementById('postFB') ) < var checker = document.getElementsByName('twitter[]'); for (var i = 0; i < checker.length; i++) < if(checker[i].checked)< return true; >>; // else fall through alert("Not enough arguments "); return false; > else < alert("Not enough arguments to submit the form"); return false; >>
wrap your checkboxes around element. Example shown:
Apply Javascript as shown.
if (document.getElementById('postTW').checked || document.getElementById('postFB')) < var myform = document.forms.myform; var elems = myform.elements['twitter[]']; for (var i = 0; i < elems.length; i++) < if (elems[i].checked) < return true; >> alert("Not enough arguments to submit the form"); return false; > else
Get the value of checked checkbox?
I just need Javascript to get the value of whatever checkbox is currently checked. EDIT: To add, there will only be ONE checked box.
If you need only one checkbox, why don’t you use radio buttons? this is the more suitable UI component for this job.
@TalYaron Can you deselect a radio buttons ? I think not without js code. Maybe the OP want to deselect the box easily.
16 Answers 16
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
Where did you get that id ? Can you please explain? The guy who asked the question used class in the input actually. It will be good if you can provide the full code so I can understand from where you got the id
This can’t work with the example code provided by OP. I’m curious why it got so many upvotes while not answering the question, although a quick fix might make it right.
surprised how this answer got many votes!! it is bad practice to use same id for multiple times in a page
@PradeepKumarPrabaharan probably people like me (not using id for multiple items) wondering why .value was giving them undefinied.
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery :
var checkedValue = null; var inputElements = document.getElementsByClassName('messageCheckbox'); for(var i=0; inputElements[i]; ++i) < if(inputElements[i].checked)< checkedValue = inputElements[i].value; break; >>
@Engineer «Saving bytes» because we must simply write document.getElementById(«foo»).value(); and «saving calculations» because getElementById is surely speedier than getElementsByTagName and a loop.
for jQuery .is(«:checked») is the correct way as .val() will return the attribute value if its defined.. and even if its not defined it will return «on» and not a boolean value.. jsfiddle.net/d5f7wnzu
document.querySelector(‘.messageCheckbox:checked’).value generates TypeError if no checkbox is checked
I am using this in my code.Try this
If the checkbox is checked x will be true otherwise it will be false.
This does not answer the question, but can be used to determine whether or not a checkbox is checked. +1 since it still helped me out.
function selectOnlyOne(current_clicked) < var cboxes = document.getElementsByName('mailId[]'); var len = cboxes.length; for (var i=0; i>
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
cb = document.getElementsByClassName('messageCheckbox')[0] cb.addEventListener('change', function())
$(document).ready(function() < var ckbox = $("input[name='ips']"); var chkId = ''; $('input').on('click', function() < if (ckbox.is(':checked')) < $("input[name='ips']:checked").each ( function() < chkId = $(this).val() + ","; chkId = chkId.slice(0, -1); >); alert ( $(this).val() ); // return all values of checkboxes checked alert(chkId); // return value of checkbox checked > >); >);
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class «messageCheckbox», otherwise you would have to do a check if the input is the checkbox type, etc.
None of the above worked for me without throwing errors in the console when the box wasn’t checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it’s part of a much bigger form submission function):
function checkbox() < var checked = false; if (document.querySelector('#opt1:checked')) < checked = true; >document.getElementById('msg').innerText = checked; >
if you using after an event occurred you can use
const selected = event.target.checked; //true or false
An example would be if you want to track selected items, here is an example using react react-hook-form react material ui, it would be better than using value from rendered field that give wrong values
. const [selectedQuestions, setSelectedQuestions] = useState(0); const handleSelectedQuestions = (checked) => < if (checked) < setSelectedQuestions((prev) =>prev + 1); > else < setSelectedQuestions((prev) =>prev - 1); > >; control= name=`> defaultValue= render= <(< field: < onChange >>) => ( item xs=> handleOpen= isLoading= isError= onChange= < handleSelectedQuestions(event.target.checked); onChange(event); >> /> )> /> .
export default function QuestionsCard(< item, handleOpen, onChange >) < return ( . onChange= sx=, >> /> > /> ) >