选择单选按钮后运行JS [英] Run JS after radio button is selected
问题描述
我有两个单选按钮,需要根据选择的单选按钮触发一个事件.问题在于它会立即触发,并且不允许用户选择一个选项.如何首先获取用户输入,然后运行JavaScript.
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.
这是代码:
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>
推荐答案
这将使他们通过使用更改函数来首先选择一个.通过给它们一个相同的名称,一次只能选择一个,这将使您返回正确的值.
从Chris的评论来看,== true
也是多余的,可以删除,因为选中的是布尔值.
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>
这篇关于选择单选按钮后运行JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!