0

I am trying to use html radio input with this code:

function change(e) { console.log(e.target.value, e.target.checked); }
<label><input type="radio" name="test" onchange="change(event)" value="sel1"> radio 1</label> <label><input type="radio" name="test" onchange="change(event)" value="sel2"> radio 2</label>

what I expect is that on change selection the change function is called 2 times, 1 for unchecked and 1 for checked, instead is called only one time. Is it the correct behavior? how can I get the expected? In this way, what is the difference between on change and on click?

I tryied with edge/chrome

2

2 Answers 2

2

MDM documentation states that the change event is fired:

"When a <input type="radio"> element is checked (but not when unchecked)"

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event

Sign up to request clarification or add additional context in comments.

Comments

0

OnChange is for one change. If the radio button is unchecked and then checked, that is one change. A user cannot uncheck a radio button.

You have not closed your input tags, ̶y̶o̶u̶ ̶h̶a̶v̶e̶ ̶d̶e̶c̶l̶a̶r̶e̶d̶ ̶t̶w̶o̶ ̶i̶n̶p̶u̶t̶s̶ ̶w̶i̶t̶h̶ ̶t̶h̶e̶ ̶s̶a̶m̶e̶ ̶n̶a̶m̶e̶.̶ This might cause unexpected behavior.

5 Comments

radio buttons SHOULD have the same name - they are a group, where only one can be selected.
... and <input> tags are void tags, must not have a closing tag.
Qoute from your link: "A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group."
True, that is why I stroke through the text. You will notice in the examples the tags are closed.
They only need to be closed in XHTML, in html both > and /> are valid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.