如何验证下拉列表中的文本框?

时间:2019-05-21 07:23:28

标签: javascript c# jquery asp.net

JavaScript

 <script>
    function isNumberKey(evt) {

        var charCode = (evt.which) ? evt.which : event.keyCode 
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            alert("Please Enter Only Numeric Value:");
            return false;
        }
        return true;
    }

    $(document).ready(function () {


        $('#TextBox2').keydown(isNumberKey);         

        $('#TextBox3').keydown(isNumberKey);
    });

</script>

这里是仅在文本框中输入数字值的代码。 当我从下拉列表中选择值时。此验证无效

Select Category:

    <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Catname" DataValueField="catId" AutoPostBack="True">                      
    </asp:DropDownList>       
  Name:

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
            <asp:RequiredFieldValidator ErrorMessage="Enter Name" ControlToValidate="TextBox1" runat="server" ForeColor="Red"></asp:RequiredFieldValidator>

    Price :<asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
                            <asp:RequiredFieldValidator ErrorMessage="Enter Price" ControlToValidate="TextBox2" runat="server" ForeColor="Red"></asp:RequiredFieldValidator>   

    Quantity
    <asp:TextBox ID="TextBox3" runat="server"  ></asp:TextBox>
                  <asp:RequiredFieldValidator ErrorMessage="Enter Quantity" ControlToValidate="TextBox3" runat="server" ForeColor="Red"></asp:RequiredFieldValidator>

当我从下拉列表中进行选择时,如何始终验证?

2 个答案:

答案 0 :(得分:1)

捕获更改事件

$("#DropDownList1").change(function () {
    var val = this.value;
    // Validation
});

答案 1 :(得分:0)

您的代码似乎没有下拉菜单中的“选择更改事件”。您应该在JQuery change事件中编写代码。或者您可以使用

$("#DropDownList1").change(function(){
 //your validation code
})

或者您可以使用OnSelectedIndexChanged()并编写C#代码进行验证

protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Your c# code
 string message = "Your Message";
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + 
"');", true);
}