使用 jQuery 检查验证单选按钮 [英] Validating a radio button is checked with jQuery

查看:18
本文介绍了使用 jQuery 检查验证单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表单上,我有一组单选按钮.这是标记:

On my form I havea set of radio buttons. Here's the mark up:

<div class="optionHolder">
    <p class="optionName">Format</p>
    <div class="option checked">
        <input type="radio" name="fileType" value="avi" />
        <img src="images/avi.png" alt="" />
        <label>AVI</label>
    </div>
    <div class="option">
        <input type="radio" name="fileType" value="mov" />
        <img src="images/mov.png" alt="" />
        <label>MOV</label>
    </div>
    <div class="option">
        <input type="radio" name="fileType" value="mp4" />
        <img src="images/mp4.png" alt="" />
        <label>MP4</label>
    </div>
    <div class="option">
        <input type="radio" name="fileType" value="mp3" />
        <img src="images/mp3.png" alt="" />
        <label>MP3</label>
        </div>
</div>

提交表单时,我想检查其中一个是否已被选中.解决这个问题的最佳方法是什么?我正在考虑循环遍历它们并设置一个标志以设置其中一个是否被选中,然后在循环后检查标志,如果它为假则抛出错误.

When the form is submitted I want to check that one of them is checked. What's the best way to go about this? I was thinking of looping through them all and making a flag to set if one of them is checked, and then check the flag after the loop and if it's false throw an error.

感谢您的帮助,干杯.

推荐答案

可以使用length等属性选择器:checked 像这样过滤选择器:

You can use the length and equal attribute selector with :checked filter selector like this:

if ($("input[name='fileType']:checked").length > 0){
  // one ore more checkboxes are checked
}
else{
 // no checkboxes are checked
}

这篇关于使用 jQuery 检查验证单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆