【问题标题】:How to validate textbox on dropdown selection?如何在下拉选择中验证文本框?
【发布时间】:2019-05-21 07:23:27
【问题描述】:

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>

当我从下拉列表中选择时如何验证所有时间?

【问题讨论】:

    标签: javascript c# jquery asp.net


    【解决方案1】:

    捕获更改事件

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

    【讨论】:

    • @Ghost 好的,你有AutoPostBack="True"。当 DropDown 更改将事件触发到服务器端时。
    • @Ghost 设置 AutoPostBack="False" 以使用 JavaScript 捕获事件
    【解决方案2】:

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

    $("#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);
    }
    

    【讨论】:

    • 您可以通过 OnSelectedIndexChanged() 中的以下代码获取所选项目 string text=DropDownList1.SelectedItem.Text;字符串值=DropDownList1.SelectedItem.Value;
    • @Ghost 然后你可以使用 JQuery 的 change() 函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2018-07-30
    • 2014-11-19
    相关资源
    最近更新 更多