需要在 Javascript 中选择单选按钮

Requiring radio button selection in Javascript

我是 JS 的初学者,试图创建一个有两个选项的单选按钮 (left/right),其中两个选项之一需要为程序 selected继续,否则会显示错误屏幕。

我有代码要么阻止参与者继续,无论他们按什么(即无论如何都会弹出错误),要么允许参与者继续的代码无论如何(即程序甚至继续如果他们不 select 一个选项。)我觉得这可能与我的逻辑运算符有关,但我真的不确定。我试过使用手动 XOR,但似乎没有问题。

我使用的是修改后的代码,所以如果我 can/should 还包含任何其他内容,请告诉我!

<div class="radio"><label><input id="option1"  name="option1" type="radio" value="Right"  />Right</label></div>
<div class="radio"><label><input id="option1" name="option1" type="radio" value = "Left" />Left</label></div>

无论如何都会导致错误的代码:

<input onclick="function filledOut(id) { return (document.getElementById(id).value == 'Left')} if(filledOut('option1') ) { next(); }else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>

导致程序继续运行的代码:

<input onclick="function filledOut(id) { return ((document.getElementById(id).value == 'Left')|| (document.getElementById(id).value == 'Right'))} if(filledOut('option1') ) { next(); } else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>

您需要将 ID 更改为其他内容。对于单选按钮,"name" 是单选按钮组。除非您要单独查看每个项目,否则您不需要 ID,如果您给它们 ID,它们需要与其他所有 ID 以及 "name" 属性不同。

https://www.w3schools.com/tags/att_input_type_radio.asp

<input id="optionRight" name="groupName" type="radio" value="Right" /> <input id="optionLeft" name="groupName" type="radio" value="Left" />

此外,您可以将其中一个单选按钮设置为默认选中。

How to select a radio button by default?

<input id="option1" name="groupName" type="radio" value="Right" checked="checked" />

据我了解,如果未检查任何内容,则需要显示错误,如果检查其中一项,则需要继续。

为此,您需要检查是否选中其中任何一个,而不是检查它的值,并为每个单选按钮指定一个唯一的 ID。 你可以做类似的事情

function isChecked(id){//Instead of filledOut
  return document.getElementById(id).checked;
 //.checked returns true or false
}
if (isChecked('option1') || isChecked('option2')){
 next();
}else{
 alert("Your error message")
}

另一个获取值的函数:

function getCheckedBtnValue(){
  if(isChecked('option1')) return document.getElementById('option1').value
  if(isChecked('option2')) return document.getElementById('option2').value
  return null
}
//You can also use this function to check if any of them is checked
const value = getCheckedBtnValue();
if(value){
 next();
}else{
 alert("Your error message");
}

此外,尽量不要在 HTML 元素内写 JavaScript ,这样经常很难阅读。 继续 JavaScripting。

<form name="formName">
    <input type="radio" name="option1" id="option1" value="Right"/>Right
    <input type="radio" name="option2" id="option2" value="Left"/>Left
</form>


<input onclick="checkResponse()" type="button" value="Continue" />

检查响应功能将检查用户单击继续按钮时是否选择了任何选项。

<script type="text/javascript">
    function checkResponse(){
        if (isChecked('option1') || isChecked('option2')){
            next();
        }else{
            alert("Your error message")
        }
    }

    function isChecked(id){

     return document.getElementById(id).checked; //returns true if any options are selected

    }

</script>