Check value checkbox javascript if checked

jQuery Checkbox Checked. Работа с чекбоксами в JS

Часто при работе с формами в HTML приходится взаимодействовать с чекбоксами, которые активируют те или иные сценарии обработки этих форм. Наиболее распространенный пример — чекбокс «Я согласен с правилами . «, который нужно отметить, чтобы кнопка отправки формы стала активной.

Другой пример — условный вывод некоторых элементов формы если выбраны какие-либо определенные опции.

Подобные задачи с легкостью решаются при помощи jQuery и нескольких строчек кода.

Как проверить чекбокс при помощи jQuery (jquery checkbox checked)

Проверить выбран ли чекбокс можно несколькими способами.

Первый и самый очевидный — проверка атрибута checked у чекбокса. Это можно сделать либо на чистом js, обратившись свойству checked

либо при помощи jQuery метода prop() , который возвращает значение атрибута, переданного в качестве аргумента. У атрибута checked может быть только два значения: true или false . Поэтому если $(‘input’).prop(‘checked’) возвращает true — считаем, что чекбокс выбран.

  

Другой способ — проверка так называемого псевдокласса :checked , который добавляется отмеченным чекбоксам. Проверить наличие псевдокласса можно при помощи jQuery метода is()

  

Псевдоклассы в CSS и jQuery — очень интересная и полезная вещь, которая заслуживает отдельной статьи. Обязательно расскажу о них поподробнее в ближайшем будущем.

Как выбрать чекбокс (checkbox check)

Предположим вам нужно отметить все чекбоксы если отмечен чекбокс «Выбрать все»

Данный функционал можно с легкостью реализовать при помощи описанного выше метода jQuery prop() с параметром checked .

$('input').prop('checked', true); // Чекбокс выбран $('input').prop('checked', false); // Чекбокс не выбран

Однако теперь мы передаем ему второй параметр — значение атрибута checked для чекбокса, в зависимости от того, отмечен ли чекбокс «Выбрать все».

   

Чтобы получить значение чекбокса, как и другого любого элемента форм ( :input ), можно воспользоваться jQuery функцией val() .

var chekbox_value = $('input[name="checkbox"]').val();

При этом не важно, отмечен чекбокс или нет. Если же нужно, например, получить значения только выбранных чекбоксов, их можно отфильтровать при помощи псевдокласса :checked

Читайте также:  Replace python несколько символов

Манипулировать чекбоксами при помощи jQuery на самом деле очень просто. Надеюсь, вы смогли в этом убедиться. Ну а если остались какие-то вопросы, буду рад на них ответить в комментариях.

Источник

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.

Источник

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