Javascript if checked is true

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.

Читайте также:  Python selenium driver get html

Чтобы сразу выполнять необходимые действия, добавим оператор 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», что в общем-то логично абсолютно. Ни о какой проверке в этакой конструкции речи не может быть. Если использовать это на нажатие кнопки «отправить сообщение». Как минимум. Следовательно, такая проверка является в корне ошибочной.

Источник

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.

Источник

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.

Источник

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.

Источник

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