Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - Run JS after radio button is selected

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...