检查是否至少选择了一个单选按钮 - JavaScript

cyb*_*ron 14 javascript

假设我有以下HTML形式:

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Choose</title>
</head>

<body>
  <form method="post" enctype="application/x-www-form-urlencoded">
    <h1>Choose</h1>

    <p><input type="radio" name="choose" value="psychology"><font size="5" color="#0033CC">Instant Psychology</font><br>
    <br>
    <input type="radio" name="choose" value="geography"><font size="5" color="#CC0000">Instant Geography</font><br>
    <br>
    <input type="radio" name="choose" value="gastronomy"><font size="5" color="#660033">Instant Gastronomy</font><br>
    <br>
    <input type="submit" name="Submit" value="Go"></p>
  </form>


</body><link rel="stylesheet" type="text/css" href="data:text/css,"></html>
Run Code Online (Sandbox Code Playgroud)

如何编写JavaScript函数以确保至少选择了一个无线电输入?

ped*_*ves 41

这样的事情应该可以解决问题

if ($("input[type=radio]:checked").length > 0) {
    // Do your stuff here
}
Run Code Online (Sandbox Code Playgroud)

更新 没有看到它不应该有jQuery,所以这里是一个替代函数来检查纯JS

 function check(){
     var radios = document.getElementsByName("choice");

     for (var i = 0, len = radios.length; i < len; i++) {
          if (radios[i].checked) {
              return true;
          }
     }

     return false;
 }
Run Code Online (Sandbox Code Playgroud)

  • 这个问题没有jQuery标签. (4认同)

Ric*_*ith 11

如果您的目标浏览器支持HTML5必需属性,则可以不使用javascript .

<input type="radio" name="choose" value="psychology" required>
<input type="radio" name="choose" value="geography" required>
<input type="radio" name="choose" value="gastronomy" required>
Run Code Online (Sandbox Code Playgroud)

请注意,在chrome中,您只需要required输入其中一个输入.我不确定其他浏览器是做什么的.

除了javascript验证(如选定的答案)之外,我通常会这样做,因此也支持html 4浏览器.


Mic*_*ski 8

循环<input>标记,检查类型以及是否选中.

function isOneChecked() {
  // All <input> tags...
  var chx = document.getElementsByTagName('input');
  for (var i=0; i<chx.length; i++) {
    // If you have more than one radio group, also check the name attribute
    // for the one you want as in && chx[i].name == 'choose'
    // Return true from the function on first match of a checked item
    if (chx[i].type == 'radio' && chx[i].checked) {
      return true;
    } 
  }
  // End of the loop, return false
  return false;
}
Run Code Online (Sandbox Code Playgroud)

这里是对jsfiddle的行动


小智 5

我这样解决了。

if(document.querySelector('input[name="choice"]:checked') == null) {
    window.alert("You need to choose an option!");
}
Run Code Online (Sandbox Code Playgroud)