简体   繁体   English

jQuery验证单选框

[英]Jquery validation for radio box

May i know how can i do validation for radio button in jquery? 我可以知道如何对jquery中的单选按钮进行验证吗? I need user to select items from the radio list, if none of the items is select when they submit the form the system will shows the error message at label. 我需要用户从单选列表中选择项目,如果在提交表单时没有选择任何项目,则系统将在标签上显示错误消息。 Any helps would be appreciated. 任何帮助将不胜感激。

Please check the jsfiddle for sample. 请检查jsfiddle示例。

Jsfiddle : 1 Demo Jsfiddle: 1 演示

use $("[name=SUBCLS]:checked").length 使用$("[name=SUBCLS]:checked").length

$('#submitbutton').click(function (e) {
    if (!$("[name=SUBCLS]:checked").length || $.trim($("#VEHNO").val()) == '') {
        e.preventDefault();
        $("#optionalerrMsg").show();
    }else{
         $("#optionalerrMsg").hide();
    }

});

UPDATED DEMO 更新的演示

DEMO 演示

id s must be always unique in the DOM so input type="radio" cannot have duplicate id s idDOM必须始终是唯一的,因此input type="radio"不能有重复的id

Instead I have added a class to your radio button and below will be the reflection of the same: 取而代之的是,我在您的radio按钮中添加了一个类,下面是相同的反映:

<input class="rds" type="radio" name="SUBCLS" id="SUBCLS" value="CO" id="CheckboxGroup1_0" style="vertical-align: -2px;" />Comprehensive
<input class="rds" type="radio" name="SUBCLS" value="TF" id="CheckboxGroup1_1" />Third Party Fire &amp; Theft
<input class="rds" type="radio" name="SUBCLS" value="TP" id="CheckboxGroup1_2" />Third Party
<div class="errmsg"></div> <!--A div to display error message-->

in your fnValidate() 在您的fnValidate()

if(!$(".rds:checked").length)
{
      $(".errmsg").text('Please select a value from radio')
}

You can simple use $("[name='SUBCLS']").is(":checked") Like this: 您可以简单地使用$("[name='SUBCLS']").is(":checked")这样:

$(document).ready(function () {
    $('#submitbutton').click(function (e) {
        var res = $("[name='SUBCLS']");
        if (!res.is(":checked")) {
            fnValidate();
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM