如何使用javascript验证Checkbox,单选按钮,下拉列表

时间:2013-03-06 04:51:16

标签: javascript asp.net validation

Product.aspx

    <asp:DropDownList id="ddlProduct" runat="server" CssClass="txtbox">
    <asp:ListItem Value="" Selected="True">Select</asp:ListItem>
    <asp:ListItem Value="Mac">Mac</asp:ListItem>
    <asp:ListItem Value="iPad">iPad</asp:ListItem>
    <asp:ListItem Value="iPhone">iPhone</asp:ListItem>
    <asp:ListItem Value="iPod">iPod</asp:ListItem>
    <asp:ListItem Value="Accessories">Accessories</asp:ListItem>
    </asp:DropDownList>
    <asp:CheckBox ID="CheckBox1" runat="server" />
    <asp:RadioButton ID="RadioButton1" runat="server" />
    <asp:Button ID="Button1" runat="server" onclick="clearForm(oForm)"/>

看到这个javascript代码:          

      $(document).ready(function () {
       $("#form1").validate({



           rules: {
               ddlCcity: { required: true },
                ddlProduct: { required: true }
           }

       });

       $.validator.addMethod(
    "select_class",
    function (value, element) {
        return this.optional(element) || (value.indexOf("--Select One--") ==-1);
    },
    "Please select a class.");

   });


    function clearForm(oForm) {
    var elements = oForm.elements;
       oForm.reset();
    for (i = 0; i < elements.length; i++) {
       field_type = elements.type.toLowerCase();
       switch (field_type) {
          case "text":
           case "password":
            case "textarea":
             case "dropdownlist":
             elements.value = "";
                break;
                case "radio":
                case "checkbox":

                if (elements.checked) {

                    elements.checked = false;

                }

                break;
            case "select-one":
            case "select-multi":

                elements.selectedIndex = 0;

                break;



            default:

                break;

        }

    }
}
    </script>

在Product.aspx中,我使用validation.js(javascript代码),但验证无效 如何使用javascript代码验证下拉列表,复选框,单选按钮

1 个答案:

答案 0 :(得分:0)

尝试以下

function validate(){
var i=0;
if($('#CheckBox1').is(":checked")==false){
i++;
}
if($('#RadioButton1').is(":checked")==false){
i++;
}
if($('#ddlProduct').val()==""){
i++;
}
if(i>0){
return false;
}else{
return true;
}
}