使用jQuery检查单选按钮的确认 [英] Validating a radio button is checked with jQuery

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

问题描述

在我的表格中,我有一组单选按钮。以下是标记:

 < div class =optionHolder> 
< p class =optionName>格式< / p>
< div class =option checked>
< input type =radioname =fileTypevalue =avi/>
< img src =images / avi.pngalt =/>
< label> AVI< / label>
< / div>
< div class =option>
< input type =radioname =fileTypevalue =mov/>
< img src =images / mov.pngalt =/>
< label> MOV< / label>
< / div>
< div class =option>
< input type =radioname =fileTypevalue =mp4/>
< img src =images / mp4.pngalt =/>
< label> MP4< / label>
< / div>
< div class =option>
< input type =radioname =fileTypevalue =mp3/>
< img src =images / mp3.pngalt =/>
< label> MP3< / label>
< / div>
< / div>

提交表单时,我想检查是否选中了其中的一个。什么是最好的方式去做这件事?我正在考虑循环遍历它们并设置一个标志来设置它们是否被选中,然后在循环之后检查标志,如果它是假的,则抛出错误。

<

解决方案

您可以使用 length 相等的属性选择器

  if($(input [name = 'fileType']:checked)。length> 0){
//一个或多个复选框被选中
}
else {
//不选择复选框
}


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.

Any help is appreciated, cheers.

解决方案

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天全站免登陆