检查是否已选中所有单选按钮

时间:2018-03-23 20:23:22

标签: javascript jquery

我正在尝试为所有输入添加公共类gender。然后我比较,如果他们没有检查,并提醒空。如何正确检查是否检查了所有按钮?

$( ".btn" ).click(function( event ) {
event.preventDefault;
if(  !$('input .gender').is(":checked") ) alert(" empty");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<input class="gender"  type="radio" name="answer[1]" value="male"> Male<br>
<input class="gender" type="radio" name="answer[1]" value="female"> Female<br>
<input class="gender" type="radio" name="answer[1]" value="other"> Other<br>
<br><br>

<input class="gender"  type="radio" name="answer[2]" value="PHP"> PHP<br>
<input class="gender" type="radio" name="answer[2]" value="Pyhon"> Python<br>
<input class="gender" type="radio" name="answer[2]" value="Java"> Java<br>
<input class="btn" type="submit" value="check">
</form>

2 个答案:

答案 0 :(得分:5)

我选择已选中的单选按钮,然后验证它们的长度是否等于无线电字段的数量:

$( ".btn" ).click(function( event ) {
  event.preventDefault();
  if ($('input[type=radio]:checked').length !== 2) console.log("at least one is empty");
  else console.log('pass')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<input class="gender"  type="radio" name="answer[1]" value="male"> Male<br>
<input class="gender" type="radio" name="answer[1]" value="female"> Female<br>
<input class="gender" type="radio" name="answer[1]" value="other"> Other<br>
<br><br>

<input class="gender"  type="radio" name="answer[2]" value="PHP"> PHP<br>
<input class="gender" type="radio" name="answer[2]" value="Pyhon"> Python<br>
<input class="gender" type="radio" name="answer[2]" value="Java"> Java<br>
<input class="btn" type="submit" value="check">
</form>

(preventDefault是一个需要运行的函数,而不是一个要声明的独立属性。)

答案 1 :(得分:0)

要达到预期效果,请使用以下选项选中是否选中所有复选框

$( ".btn" ).click(function(event) {
event.preventDefault;
  var checkboxList = $('.gender')
  var isEmpty = true

$.each(checkboxList,function(i,v){
  console.log("is "+v.value+" checked -->"+v.checked)
  if(v.checked){
    isEmpty = false;
  }
})

  if(isEmpty){
    alert(" empty");
  }
});

代码示例 - https://codepen.io/nagasai/pen/dmzMgo?editors=1011

<强>解释

$(&#39; .gender&#39;)检索所有复选框并将其循环到$ .each并检查每个字段是否已选中。
检查标志isEmpty然后根据

发出警报