Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two radio buttons and that needs to fire a event according to what radio button is selected. Problem is that it fires immediately and doesn't let the user select an option. How I can get the user's input first and then run the JavaScript.

Here is the code:

if (document.getElementById("radio_myself").checked == true) {
  alert(document.getElementById("radio_myself").value);
} else {
  alert(document.getElementById("radio_selse").value);
}
<span><input id="radio_myself" name="radMyself" type="radio" value="Myself"/>Myself</span>
<span><input id="radio_selse" name="radSelse" type="radio" value="Someone"/>Someone Else</span>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

This will make them select one first by using a function on change. By giving them the same name only one at a time can be selected, this will let you return the correct value. From Chris's comment Also == true is redundant and can be removed, because checked is a boolean.

function check() {
  if (document.getElementById("radio_myself").checked) {
    alert(document.getElementById("radio_myself").value);
  } else {
    alert(document.getElementById("radio_selse").value);
  }
}

addEventListener("change", ({target}) => { if(target.matches("input[type='radio']")){ check(); } })
<span><input id="radio_myself" name="radSelse" type="radio" value="Myself"/>Myself</span>
<span><input id="radio_selse" name="radSelse" type="radio" value="Someone"/>Someone Else</span>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...