- JavaScript Checkbox
- Creating an HTML checkbox
- Checking if a checkbox is checked
- Getting checkbox values
- Getting values of multiple selected checkboxes
- Check / Uncheck all checkboxes
- Creating checkboxes dynamically
- Summary
- Как выбрать или убрать все флажки в чекбоксах с помощью JavaScript
- Посмотреть результат
JavaScript Checkbox
Summary: in this tutorial, you will learn how to use JavaScript to test if a checkbox is checked, get the values of selected checkboxes, and select/unselect all checkboxes.
Creating an HTML checkbox
To create a checkbox, you use the element with the type of checkbox as follows:
input type="checkbox" id="accept">
Accept Code language: HTML, XML (xml)
It’s a good practice to always associate a checkbox with a label to improve usability and accessibility. By doing this, clicking the label also checks or unchecks the checkbox.
label for="accept">
input type="checkbox" id="accept" name="accept" value="yes"> Accept label>Code language: HTML, XML (xml)
input type="checkbox" id="accept" name="accept" value="yes">
label for="accept"> Accept label>Code language: HTML, XML (xml)
Note that the for attribute’s value of the label must match the id of the checkbox.
The following works but is bad practice so you should avoid it:
input type="checkbox" id="accept" name="accept" value="yes">
AcceptCode language: HTML, XML (xml)
Checking if a checkbox is checked
A checkbox has two states: checked and unchecked.
To get the state of a checkbox, you follow these steps:
- First, select the checkbox using a DOM method such as getElementById() or querySelector() .
- Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
See the following example:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Checkbox title> head> body> label for="accept"> input type="checkbox" id="accept" name="accept" value="yes"> Accept label> script> const cb = document.querySelector('#accept'); console.log(cb.checked); // false script> body> html>Code language: HTML, XML (xml)
First, create the HTML checkbox element:
label for="accept">
input type="checkbox" id="accept" name="accept" value="yes"> Accept label>Code language: HTML, XML (xml)
Second, select the checkbox with id #accept and examine the checked property:
const cb = document.querySelector('#accept'); console.log(cb.checked);
Code language: JavaScript (javascript)
Because the checkbox is unchecked, you’ll see false in the console:
false
Code language: JavaScript (javascript)
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Checkbox title> head> body> label for="accept"> input type="checkbox" id="accept" name="accept" value="yes"> Accept label> script> const checked = document.querySelector('#accept:checked') !== null; console.log(checked); // false script> body> html>Code language: HTML, XML (xml)
In this example, the selector #accept:checked selects the element with the id #accept and has the attribute checked . For example, it matches the following element:
input type="checkbox" id="accept" checked>
AcceptCode language: HTML, XML (xml)
input type="checkbox" id="accept">
AcceptCode language: HTML, XML (xml)
Therefore, if the checkbox element with the id #accept is checked, the document.querySelector() will return it. On the console window, you’ll see the value false because the checkbox is unchecked:
false
Code language: JavaScript (javascript)
Getting checkbox values
The following page shows a checkbox and a button. When you click the button, you’ll see the checkbox’s value on the console window:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Checkbox title> head> body> label for="accept"> input type="checkbox" id="accept" name="accept"> Accept label> button id="btn">Submit button> script> const cb = document.querySelector('#accept'); const btn = document.querySelector('#btn'); btn.onclick = () => < alert(cb.value); >; script> body> html>Code language: HTML, XML (xml)
When you get the value attribute of a checkbox, you always get the ‘on’ string whether the checkbox is checked or not.
Getting values of multiple selected checkboxes
The following page shows three checkboxes. If you select one or more checkboxes and click the button, it’ll show the values of the selected checkbox:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Checkboxes title> head> body> p>Select your favorite colors: p> label for="c1"> input type="checkbox" name="color" value="red" id="c1">Red label> label for="c2">input type="checkbox" name="color" value="green" id="c2"> Green label> label for="c3">input type="checkbox" name="color" value="blue" id="c3">Blue label> p> button id="btn">Get Selected Colors button> p> script> const btn = document.querySelector('#btn'); btn.addEventListener('click', (event) => < let checkboxes = document.querySelectorAll('input[name="color"]:checked'); let values = []; checkboxes.forEach((checkbox) => < values.push(checkbox.value); >); alert(values); >); script> body> html>Code language: HTML, XML (xml)
In the HTML, we create three checkbox elements with the same name (color) but distinct values:
label for="c1">
input type="checkbox" name="color" value="red" id="c1">Red label> label for="c2">input type="checkbox" name="color" value="green" id="c2">Green label> label for="c3">input type="checkbox" name="color" value="blue" id="c3">Blue label>Code language: HTML, XML (xml)
First, add the click event handler to the button:
const btn = document.querySelector('#btn'); btn.addEventListener('click', (event) => < // . >);
Code language: JavaScript (javascript)
Second, select the selected checkboxes using the document.querySelectorAll() method inside the click event handler:
let checkboxes = document.querySelectorAll('input[name="color"]:checked');
Code language: JavaScript (javascript)
Third, push the values of the selected checkboxes to an array:
let values = []; checkboxes.forEach((checkbox) => < values.push(checkbox.value); >); alert(values);
Code language: JavaScript (javascript)
Check / Uncheck all checkboxes
The following page has three checkboxes and a button. When you click the button, if the checkboxes are checked, they will be unchecked and vise versa:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Check/uncheck checkboxes title> head> body> p> button id="btn">Check / Uncheck All button> p> label for="c1">input type="checkbox" name="color" value="red" id="c1"> Red label> label for="c2">input type="checkbox" name="color" value="green" id="c2"> Green label> label for="c3"> input type="checkbox" name="color" value="blue" id="c3">Blue label> script> function check(checked = true) < const checkboxes = document.querySelectorAll('input[name="color"]'); checkboxes.forEach((checkbox) => < checkbox.checked = checked; >); > function checkAll( ) < select(); this.onclick = uncheckAll; > function uncheckAll( ) < select(false); this.onclick = checkAll; > const btn = document.querySelector('#btn'); btn.onclick = checkAll; script> body> html>Code language: HTML, XML (xml)
First, define the check() function that checks or unchecks all checkboxes with the name «color» :
function check(checked = true) < const checkboxes = document.querySelectorAll('input[name="color"]'); checkboxes.forEach((checkbox) => < checkbox.checked = checked; >); >
Code language: JavaScript (javascript)
When you click the button, it checked all the checkboxes. And. If you click the button again, it should uncheck all the checkboxes. To do this switch, you need to reassign the click event handler whenever the click event fires.
Second, select the #btn button and assign the checkAll() function to the onclick property of the button:
const btn = document.querySelector('#btn'); btn.onclick = checkAll;
Code language: JavaScript (javascript)
Third, define the checkAll() function that checks all the checkboxes:
function checkAll( ) < check(); this.onclick = uncheckAll; >
Code language: JavaScript (javascript)
Finally, define the uncheckAll() function that unchecks all the checkboxes:
function uncheckAll( ) < check(false); this.onclick = checkAll; >
Code language: JavaScript (javascript)
Creating checkboxes dynamically
The following example shows how to create checkboxes dynamically using JavaScript:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Checkboxes title> head> body> div id="root"> div> script> const colors = ["Red","Green","Blue"]; colors.forEach((color)=>< // generate id const >`color-$ `; // create a label const label = document.createElement('label'); label.setAttribute("for", id); // create a checkbox const checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.name = "color"; checkbox.value = color; checkbox.id = id; // place the checkbox inside a label label.appendChild(checkbox); // create text node label.appendChild(document.createTextNode(color)); // add the label to the root document.querySelector("#root").appendChild(label); >); script> body> html>Code language: HTML, XML (xml)
div class="output-cont">
div class="output"> iframe height="250px" src="https://www.javascripttutorial.net/sample/dom/checkbox/checkbox-dynamic.html"> iframe> div> div>Code language: HTML, XML (xml)
First, define an array that consists of three strings. In practice, you may have the array that comes from the result of an API call:
const colors = ["Red","Green","Blue"];
Code language: JavaScript (javascript)
Second, iterate over the array elements and:
1) Generate a unique id for each checkbox:
const >`color-$ `;
Code language: JavaScript (javascript)
2) Create a label and assign the id to the for attribute:
const label = document.createElement('label'); label.setAttribute("for", id);
Code language: JavaScript (javascript)
const checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.name = "color"; checkbox.value = color; checkbox.id = id;
Code language: JavaScript (javascript)
4) Place the checkbox inside the label:
label.appendChild(checkbox);
Code language: CSS (css)
5) Create a text node and append it to the label:
label.appendChild(document.createTextNode(color));
Code language: CSS (css)
6) Add the label to the root element:
document.querySelector("#root").appendChild(label);
Code language: CSS (css)
The following example also dynamically generates checkboxes like the above example:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Checkboxes title> head> body> div id="root"> div> script> const colors = ["Red","Green","Blue"]; const html = colors.map(color => ` ` ).join(' '); document.querySelector("#root").innerHTML = html; script> body> html>Code language: HTML, XML (xml)
- First, generate a label and checkbox element using the Array map() method and template literals.
- Second, join the HTML strings into a single HTML using the String join() method.
- Third, append the HTML to the #root element.
Summary
- Use the element with the type checkbox to create a checkbox element.
- Place a checkbox inside a label element to improve the usablity and accessibility.
- Use checkbox.checked property or :check selector to test if a checkbox is checked.
- Get the value attribute to get the value of a checkbox.
Как выбрать или убрать все флажки в чекбоксах с помощью JavaScript
В этом руководстве мы расскажем, как ставить и снимать флажки в input type checkbox с помощью JavaScript . Пользователь сможет одним кликом включить или выключить все элементы списка, что значительно сэкономит его время.
Посмотреть результат
Чтобы установить или убрать все флажки в чекбоксах, нужно:
Шаг 1 . Создайте HTML файл , сделайте его разметку, примените стили и напишите код JavaScript .
Мы создали файл HTML и сохранили его как checkbox.html :
body < width:100%; margin:0 auto; padding:0px; background-color:#424242; font-family:helvetica; >#wrapper < text-align:center; margin:0 auto; padding:0px; width:100%; >h1 < margin-top:50px; color:#D8D8D8; >h1 p < font-size:14px; color:white; >input[type="button"] < background:none; color:white; border:1px solid white; width:100px; height:50px; border-radius:50px; margin:10px; font-weight:bold; >input[type="checkbox"] < width:20px; height:20px; >td
PHP HTML JavaScript jQuery CSS MySQL
Мы написали разметку для input type checkbox JavaScript , и создали две кнопки: одна для того, чтобы выбрать все элементы списка, другая – чтобы отменить выбор всех элементов списка. Две функции – check() и uncheck() ставят или убирают галочки всех чекбоксов. Функция check() проверяет, является ли элемент чекбоксом. Если да, она ставит в нем галочку. Функция uncheck() работает точно так же, как и check() , только снимает галочки со всех чекбоксов.
Вот и все, выбирать или снимать все флажки в input type checkbox при помощи JavaScript просто! Вы можете изменять этот код на ваше усмотрение. Пожалуйста, оставляйте комментарии в форме снизу.