Как узнать checked js

How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

But the following code returns false by default:

How do I successfully query the checked property?

67 Answers 67

How do I successfully query the checked property?

The checked property of a checkbox DOM element will give you the checked state of the element.

Given your existing code, you could therefore do this:

However, there’s a much prettier way to do this, using toggle :

Use jQuery’s is() function:

Using the new property method:

jQuery 1.6+

jQuery 1.5 and below

Any version of jQuery

All credit goes to Xian.

I am using this and this is working absolutely fine:

Note: If the checkbox is checked it will return true otherwise undefined, so better check for the «TRUE» value.

Since jQuery 1.6, the behavior of jQuery.attr() has changed and users are encouraged not to use it to retrieve an element’s checked state. Instead, you should use jQuery.prop() :

Two other possibilities are:

This worked for me:

Where isAgeSelected is the id of the control.

Also, @karim79’s answer works fine. I am not sure what I missed at the time I tested it.

Note, this is answer uses Microsoft Ajax, not jQuery

Hope it helps :)- Thanks.

This can help if you want that the required action has to be done only when you check the box not at the time you remove the check.

Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself!

Ideally, you’d want to put your code into a change event handler such as it is fired every time the value of the check box is changed (independent of how it’s done so).

I believe you could do this:

I decided to post an answer on how to do that exact same thing without jQuery. Just because I’m a rebel.

First you get both elements by their ID. Then you assign the checkboxe’s onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately. In that example using the ternary operator.

Here is a fiddle for you to test it.

Addendum

If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline.

Источник

Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?

13 Answers 13

Important behaviour that has not yet been mentioned:

Programmatically setting the checked attribute, does not fire the change event of the checkbox.

(Fiddle tested in Chrome 46, Firefox 41 and IE 11)

The click() method

Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click() method of the checkbox element, like this:

Setting checked to a specific value

You could test the checked attribute, before calling the click() method. Example:

We can checked a particulate checkbox as,

Как узнать checked js. Смотреть фото Как узнать checked js. Смотреть картинку Как узнать checked js. Картинка про Как узнать checked js. Фото Как узнать checked js

Try This:

Как узнать checked js. Смотреть фото Как узнать checked js. Смотреть картинку Как узнать checked js. Картинка про Как узнать checked js. Фото Как узнать checked js

I would like to note, that setting the ‘checked’ attribute to a non-empty string leads to a checked box.

So if you set the ‘checked’ attribute to «false», the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.

For single check try

Как узнать checked js. Смотреть фото Как узнать checked js. Смотреть картинку Как узнать checked js. Картинка про Как узнать checked js. Фото Как узнать checked js

Note that doing so does not fire the normally related event (change) so you’ll need to manually fire it to have a complete solution that works with any related event handlers.

Here’s a functional example in raw javascript (ES6):

If you run this and click on both the checkbox and the button you should get a sense of how this works.

Источник

Как в jQuery проверить checkbox

Дата публикации: 2016-09-12

Как узнать checked js. Смотреть фото Как узнать checked js. Смотреть картинку Как узнать checked js. Картинка про Как узнать checked js. Фото Как узнать checked js

От автора: приветствую вас, друзья. Из этой небольшой статьи вы узнаете, как в jQuery проверить, отмечен ли checkbox формы. Это достаточно полезная вещь, поскольку часто, в зависимости от того, был ли отмечен чекбокс, программа должна работать по тому или иному сценарию.

Исходные файлы текущей статьи вы можете скачать по ссылке.

Итак, перед нами стоит задача проверить checkbox средствами jQuery. К примеру, мы хотим реализовать следующий функционал. У нас есть кнопка отправки формы, которая изначально не активна. И, если пользователь отметил checkbox, мы должны активировать кнопку. Давайте попробуем. Для начала создадим простенькую форму:

Как узнать checked js. Смотреть фото Как узнать checked js. Смотреть картинку Как узнать checked js. Картинка про Как узнать checked js. Фото Как узнать checked js

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Для того, чтобы форма выглядела красиво и при этом не пришлось писать стили, я использую CSS фреймворк Bootstrap. В итоге получилась вот такая симпатичная форма. При этом, благодаря атрибуту disabled, кнопка не активна.

Как узнать checked js. Смотреть фото Как узнать checked js. Смотреть картинку Как узнать checked js. Картинка про Как узнать checked js. Фото Как узнать checked js

Ну что же, осталось лишь реализовать функционал, который разблокирует кнопку при отметке чекбокса и вновь заблокирует ее, если отметку снять. С jQuery это пустяковая задача, которая решается буквально несколькими строками кода.

Для решения задачи воспользуемся методом prop() со значением checked, который вернет true или false в зависимости от того, отмечен checkbox или нет. Код будет таким:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *