checked radio input javascript

Получить или отметить

Для тега есть свойство selectedIndex , которая возвращает индекс активного пункта (порядок начинается с нуля).

Сделать активным нужный пункт можно также через свойство selectedIndex .

Получить или отметить checkbox

Выбрать активные чекбоксы можно через фильтр :checked .

Чтобы отметить нужный чекбокс, надо для его свойства checked указать true .

Получить или отметить radio

Выбрать активный пункт переключателя можно через фильтр :checked .

Метод querySelectorAll() возвращает все указанные объекты. Т.к. у переключателя может быть только один отмеченный пункт, то в коде выше используется querySelector() , который возращает только один объект.

Чтобы отметить нужный пункт переключателя, надо для его свойства checked указать true .

I have a radio input group. If a radio is checked and I click again it becomes unchecked.

Is there a way to get the previous status of the radio onClick event?

10 Answers 10

But again, this is not how radio buttons are intended to be used. I think you’d be better of with a set checkbox’es where you could uncheck all other checkboxes than the current clicked (hence always max 1 selected)

Its quite simple. Just follow the simple example and

Just find the length and make every index checked=true/false.

I had the same problem and figured it out. None of the answers above work exactly as I wanted — most of them require an additional button to reset the radio. The goal was to uncheck radio by clicking on the radio itself.

The problem was very complicated because the radio button value changes BEFORE the click event fires so when we’re listening to the event we can’t tell if the radio button was already checked or not. In both cases it is already checked. Another approach was to listen to mousedown event. Unlike click , it fires before changing radio checked attribute but unchecking it inside event handler gives us nothing since it is checked back again during mouseup event.

My answer is a little ugly workaround so I generally don’t suggest it to others and I’ll probably abandon it myself. It works but it involves 20ms timeout function which I’m not fond of in cases like this.

Here is the code explanation:

As a timeout function I could use a string (less writing) but as far as I know it would be eval ‘ed. Though I don’t trust eval function, I prefered anonymous function.

One more thing — one could ask why spreading the code into two separate event handlers while we can fire the timeout function on mousedown? Well, what if someone press the mouse on a radio and holds it for a few secs or even someone is simply a very slow person ;). Generally, with this solution we omit the problem of lag between mousedown and mouseup .

If you need some more info about dataset , here’s the MDN reference: This property came with HTML5 and might be not cross-browser, I guess, so if you want 100% compatibility, replace it with any other solution that’ll contain the data, you name it.

Sorry about jQuery here and there but I hope you’re fine with it — it was much easier that way.

лабораторные работы и задачи по программированию и информатике, егэ по информатике

Объект javascript checkbox

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

Свойства элемента checkbox:

  • checked — содержит булево значение true или false, в зависимости от того, отмечен или нет данный флажок;
  • name — соответствует атрибуту name тега input
  • value — соответствует атрибуту value тега input
  • type — для объектов checkbox значением этого атрибута является строка checkbox

    Свойство checked

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

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

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