Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between onClick() and onChange() for radio buttons

<input type="radio" name="group" value="book_folder" onchange="makeRadioButtons()">Create New Book</input>  <input type="radio" name="group" value="book_chapter" onchange="makeCheckBoxes()">Create New Chapter</input> 

I was using the above code and when I clicked the second radio button, I thought I should get two events, one from the button that got unchecked and other from the button that got checked, because logically speaking, both buttons got their state changed, and I have bound the onchange() event not the onclick() event. But as it seems I only get one event from the button that just got checked. Is this a desired behaviour in HTML? How can I get an event from the button if it got unchecked?

like image 628
samach Avatar asked Jul 06 '11 12:07

samach


People also ask

What is OnClick and Onchange?

Internet Explorer only fires the onchange event when the checkbox loses the focus (onblur). So onclick is more of a cross browser solution. onchange happens only after the element lose focus. (You wont see a difference since you are calling alert and losing focus on every change).

Can we use OnClick on radio button?

Responding to Click Events When the user selects one of the radio buttons, the corresponding RadioButton object receives an on-click event. To define the click event handler for a button, add the android:onClick attribute to the <RadioButton> element in your XML layout.

Does radio button have Onchange?

Yes there is no change event for currently selected radio button.

Can I use Onchange in button?

Definition and Usage The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event.


1 Answers

Use this to get the desired behavior:-

var ele = document.getElementsByName('group'); var i = ele.length; for (var j = 0; j < i; j++) {     if (ele[j].checked) { //index has to be j.         alert('radio '+j+' checked');     }     else {         alert('radio '+j+' unchecked');     } } 

Hope it helps.

like image 109
Knowledge Craving Avatar answered Oct 08 '22 18:10

Knowledge Craving