Setting checkbox checked in javascript

Checking and unchecking a checkbox with JavaScript: a quick lesson on HTML IDL attributes

I had a list of checkboxes, with one «select all» checkbox at the top. When the «select all» checkbox is checked, I wanted to check all the underlying checkboxes. I tried setting the checked attribute on the input elements. My code looked something like this:

const selectAllCheckbox = document.getElementById('select-all'); const childCheckboxes = document.querySelectorAll('.child-checkbox'); const toggleSelectAllCheckbox = () =>  const areAllChecked = [. childCheckboxes].every(c => c.hasAttribute('checked')); if (areAllChecked)  // uncheck all if every checkbox is checked childCheckboxes.forEach(c =>  c.removeAttribute('checked'); >) > else  // otherwise, check all childCheckboxes.forEach(c =>  c.setAttribute('checked', ''); >) > > selectAllCheckbox.addEventListener('click', toggleSelectAllCheckbox); 

This seems alright at first glance. If you toggle the «select all» checkbox it works. However, if you toggle any of the child checkboxes then toggle «select all», it ignores the children you just toggled. Try it out in the Codepen example above. This won’t do.

✅ Setting the «checked» property

Eventually, I figured out using the setAttribute() and removeAttribute() methods was where I was going wrong. Instead, I needed to access and set the checked property directly, like so:

const selectAllCheckbox = document.getElementById('select-all'); const childCheckboxes = document.querySelectorAll('.child-checkbox'); const toggleSelectAllCheckbox = () =>  const areAllChecked = [. childCheckboxes].every(c => c.checked === true) childCheckboxes.forEach(c =>  c.checked = !areAllChecked; >) > selectAllCheckbox.addEventListener('click', toggleSelectAllCheckbox); 

There is some extra work to make sure the «select all» checkbox updates when toggling the children, but you can check out the Codepen for that.

Why was I wrong?

When it comes to setting attributes on HTML elements, I had always assumed element.setAttribute(‘attribute’, value) was roughly interchangeable with element.attribute = value . But there is a subtle difference. HTML attributes have two sides, the content attribute and the IDL attribute. The content attribute is what is written in HTML. It is also accessed via the methods element.hasAttribute() , element.getAttribute() , element.setAttribute() , and element.removeAttribute() . For example, if I have , checkboxElement.hasAttribute(‘checked’) will be false. If I then set checkboxElement.setAttribute(‘checked’) and use a devtools inspector, my HTML will now be . Screenshot of a checkbox element in Firefox devtools inspector. The IDL attribute is a JavaScript property. If I log my element to the console with console.log(‘checkboxElement’) , I can drill into it like any JavaScript object and see all the properites. These are the IDL attributes. Screenshot of a checkbox element logged to the Firefox developer console. A list of properties, including The IDL attribute will use the underlying content attribute. element.setAttribute(«attribute», value) and element.attribute = value are interchangable. most of the time. The catch with checkboxes is that, for the checked IDL attribute, the underlying content attribute is not checked . It doesn’t have one. The content attribute checked for inputs with type=»checkbox» instead corresponds to the defaultChecked IDL attribute. Even though element.setAttribute(«checked») sort of works for programatically checking a checkbox (at least in the browsers I tried), it’s not supposed to. Use the checked content attribute if you want the checkbox checked by default at page load (or when the element is first painted). If you want to mutate the checkbox with JavaScript, use the checked IDL attribute: element.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.

Источник

Set Checkbox as Checked in JavaScript

To set a checkbox as checked using JavaScript, the simplest way is to target the input element and change its checked property to true.

document.getElementById("checkboxInput").checked = true;

If we want to uncheck a checkbox using JavaScript, we can target the input element and change its checked property to false:

document.getElementById("checkboxInput").checked = false;

Let’s say we have the following HTML:

To set the first checkbox as checked, we can use the getElementById() method to target its checked property:

document.getElementById("checkbox-1").checked = true;

How to Set a Checkbox as Checked on Click with JavaScript

We can check a checkbox using JavaScript very easily by combining the checked property with a click event.

Let’s say we have the following HTML code and we want to set the checked value of our checkbox as checked in the HTML below:

We can utilize an onclick event and getElementById() method to set the checked property of the checkbox.

Below is the JavaScript code which will allow us to set our checkbox as checked.

The final code and output for this example of how to check a checkbox on click using JavaScript is below:

 
Check Checkbox

How to Uncheck a Checkbox Using JavaScript

Just as easily as we can check a checkbox, we can also uncheck a checkbox using JavaScript.

Let’s say we have the following HTML code and we want to set the checked value of our checkbox as unchecked in the HTML below:

 
Uncheck Checkbox

We can once again utilize an onclick event and getElementById() method to set the checked property of the checkbox to false.

Below is the JavaScript code which will allow us to set our checkbox as unchecked.

The final code and output for this example of how to uncheck a checkbox on click using JavaScript is below:

 
Uncheck Checkbox

Hopefully this article has been useful for you to understand how to check a checkbox and uncheck a checkbox using JavaScript.

  • 1. Using JavaScript to Get a Random Number Between Range of Numbers
  • 2. Using JavaScript to Remove Leading Zeros
  • 3. How to Remove All Numbers From String in JavaScript
  • 4. Using JavaScript to Create a Unique Array
  • 5. How to Repeat Character N Times in JavaScript
  • 6. JavaScript onkeydown – How to Use onkeydown Event with JavaScript
  • 7. Using Javascript to Remove Class from Element
  • 8. Creating a JavaScript Function to Add Two Numbers
  • 9. Using JavaScript to Check a Radio Button
  • 10. How to Change the Id of an Element in JavaScript

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

JavaScript урок12. Объектная модель документа (продолжение): идентификация в javascript checkbox и radio

егэ разбор егэ разбор pascal уроки c уроки python уроки c++ уроки vb уроки lazarus уроки php уроки html уроки css уроки javascript уроки jquery и ajax уроки prolog уроки flash уроки

На уроке рассматриваются способы доступа в javascript к checkbox (флажкам) и radio (радио-кнопкам или переключателям). Разбирается принцип работы со свойством checked для осуществления проверки radio и checkbox

Объект javascript checkbox

form name="f1"> input type="checkbox" name="yourName" id="ch1"> Да /form>

Элемент checkbox идентифицируется:

document.getElementById('ch1').checked=true;

Пример: По щелчку на элементе флажок (checkbox) выводить диалоговое окно с сообщением для подтверждения: «Номер люкс очень дорогой. Вы уверены?». Скрипт описать в качестве значения атрибута.

input type="checkbox" name="checkbox1" value="Номер Люкс" onсlick=" confirm('Номер люкс очень дорогой. Вы уверены?')">Номер люкс

Свойство checked

Пример: По загрузке страницы устанавливать флажок (checkbox) отмеченным

1 способ (через name ):
В скрипте:

function check(){ document.f1.ch1.checked=true; }
body onload="check()"> form name="f1"> input type="checkbox" name="ch1">пункт1br> input type="checkbox" name="ch2">пункт2br> /form> …

2 способ (через id ):
В скрипте:

function check(){ ch1.checked=true; }
body onload="check()"> input type="checkbox" id="ch1">пункт1br> input type="checkbox" id="ch2">пункт2br>

checkbox javascript

Задание js12_1. Создать страницу проверки знаний учащегося с одним вопросом и тремя ответами на вопрос: два из них правильные и один неправильный. Осуществить проверку правильности отмеченных при помощи элементов формы checkbox ответов. Функцию проверки запускать по щелчку кнопки

Объект переключатель в javascript — radio и свойство checked

Элемент javascript radio предназначен для выбора только одного единственного варианта из нескольких.

Для того, чтобы несколько переключателей работали сгруппировано, т.е. чтобы при выборе одного radio все остальные бы отключались, необходимо для всех radio установить одинаковое значение атрибута name

Рассмотрим пример использования радиокнопок:
html-код:

body> form name="f1"> Ваш пол:br> input type="radio" name="r1" id="id1"br> input type="radio" name="r1" id="id2"br> input type="button" onclick="fanc()"> /form> /body>

Группа радиокнопок (radio) идентифицируется в скрипте следующим образом:
Скрипт:

function fanc(){ document.getElementById("id1").checked=true; // 1-й способ document.f1.r1[0].checked=true; // 2-й способ document.f1['r1'][0].checked=true; // 3-й способ }

Первый способ является наиболее предпочтительным.

Рассмотрим пример использования в javascript radio с checked свойством:

1 способ:
Скрипт:

function fanc(){ idr1.checked=true; }
input type="radio" name="r1" id="idr1">пункт1br> input type="radio" name="r1" id="idr2">пункт1br> input type="button" onClick ="fanc()" value="отметить">

2 способ:
Скрипт:

function fanc(){ document.f1.r1[0].checked=true; }
form name="f1"> input type="radio" name="r1">пункт1br> input type="radio" name="r1">пункт1br> input type="button" onClick ="fanc()" value="отметить"> /form>

radio в javascript

Задание js12_2.
Создать страницу проверки знаний учащегося с вопросом: «Какой заряд у электрона?» и двумя ответами: «положительный» (неправильный) и «отрицательный» (правильный). Осуществить проверку правильности отмеченного при помощи элемента формы radio ответа. Функцию проверки запускать по щелчку кнопки

Источник

Читайте также:  Php get length in bytes
Оцените статью