Проверить нажат ли чекбокс javascript

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.

Источник

Checkbox Checked — Проверка Состояния Чекбокса ✔️

В данной статье мы разберём различные способы проверки состояния чекбоксов. Это необходимо для эффективной работы с элементами форм.

1. Проверка checkbox на checked — метод .is()

Сначала научимся определять при клике состояние текущего checkbox (checked / unchecked).

$(".checkbox").on("click", function () < if ($(this).is(":checked")) < // checkbox checked >else < // checkbox unchecked >>)

Т.о. при клике на чекбокс, мы отлавливаем событие click у текущего checkbox $(this) и с помощью метода .is() мы проверяем наличие псевдокласса :checked.

2. Проверка checkbox/radio на состояние (выбран/не выбран) — метод .prop()

Воспользуемся методом .prop() для проверки состояния checkbox или radio input.

Данный код возвращает true или false при нажатии на чекбокс или радио input.

Чтобы сразу выполнять необходимые действия, добавим оператор if :

2.1 Отметить / снять checked

Также при помощи метода .prop() можно отметить (или снять состояние checked).

// добавим checked $(".checkbox").prop("checked", true) // удалим состояние checked $(".checkbox").prop("checked", false) // добавим состояние checked для всех чекбоксов $("input:checkbox").prop("checked", true); // удалим checked для всех чекбоксов $("input:checkbox").prop("checked", false);

2.2 Деактивация чекбокса

Чтобы деактивировать/активировать чекбокс, воспользуйтесь следующим кодом:

// отключаем чекбокс $(".checkbox").prop("disabled", true) // включаем чекбокс $(".checkbox").prop("disabled", false)

3. Имитация клика по чекбоксу

Чтобы имитировать клик по чекбоксу, воспользуйтесь следующим кодом:

4. Найти все выбранные checkbox / radio — селектор :checked

При помощи селектора :checked найдём все выбранные checkbox / radio.

Теперь рассмотрим пример с input type=»checkbox» , это также отлично работает и с radio input.

const inputs = document.querySelectorAll("input"); const container = document.querySelector(".container"); inputs.forEach(el => < el.addEventListener("click", () => < container.textContent = ""; let input_checks = document.querySelectorAll("input:checked"); input_checks.forEach(el_checked =>< container.insertAdjacentHTML("beforeend", el_checked.value); >); >); >);

5. Подсчёт количества выбранных чекбоксов

Чтобы узнать количество выбранных checkbox, будем использовать свойство .length :

const myCount = function () < $("#output_field").html($(".count-checked:checked").length + " чекбоксов выбрано вами."); >; myCount(); $("input").on("click", myCount);

6. Запрет отправки формы без выбора чекбокса

Создадим форму, отправить данные которой пользователь сможет только после выбора checkbox.

Работа с JavaScript. Проверка checkbox на checked :

$("#checked").on("change", function () < if ($("#checked").prop("checked")) < $(".form__submit").attr("disabled", false); >else < $(".form__submit").attr("disabled", true); >>);

Как вы помните из 2 примера, .prop(«checked») возвращает true или false — то что нам и нужно.

const checkbox = document.getElementById("checked"); const btn_submit = document.querySelector(".form__submit"); checkbox.addEventListener("change", () => < if (checkbox.checked) < btn_submit.removeAttribute("disabled"); >else < btn_submit.setAttribute("disabled", true); >>);

7. Массив значений выбранных чекбоксов

Получим массив значений из выбранных чекбоксов.

$(".array-checked").on("change", function () < const arrayChecked = []; $(".array-checked:checked").each(function () < arrayChecked.push($(this).val()); >); console.log(arrayChecked); >);

Возможно вам так же будет интересна статья про стилизацию чекбоксов.

8. Проверка checkbox на checked на чистом JavaScript

Используя чистый JavaScript определим состоние чекбокса.

const checkbox = document.querySelector(".checkbox"); checkbox.addEventListener("change", function () < if (this.checked) < console.log("checked"); >else < console.log("unchecked"); >>)

Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки, то можете следить за выходом новых статей в Telegram.

Статьи из данной категории:

Комментарии ( 3 )

«if ( $(this).prop(‘checked’, true) )» Ты ещё раз проверь. точно уверен, что это проверка? Ибо у меня это работает именно как «установить свойство checked в значение true», что в общем-то логично абсолютно. Ни о какой проверке в этакой конструкции речи не может быть. Если использовать это на нажатие кнопки «отправить сообщение». Как минимум. Следовательно, такая проверка является в корне ошибочной.

Источник

Input Checkbox checked Property

The checked property sets or returns the checked state of a checkbox. This property reflects the HTML checked attribute.

Browser Support

Syntax

Property Values

Technical Details

Return Value: A Boolean, returns true if the checkbox is checked, and false if the checkbox is not checked

More Examples

Example

Find out if a checkbox is checked or not:

Example

Use a checkbox to convert text in an input field to uppercase:

Example

Several checkboxes in a form:

var coffee = document.forms[0];
var txt = «»;
var i;
for (i = 0; i < coffee.length; i++) if (coffee[i].checked) txt = txt + coffee[i].value + " ";
>
>
document.getElementById(«order»).value = «You ordered a coffee with: » + txt;

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью