根据从DropDownList中选择的项目,将min和max设置为TextBox?

时间:2018-04-27 05:09:17

标签: javascript jquery asp.net

是否有一种方法可以从客户端更改TextBox的最小和最大长度并验证类似rangevalidator,具体取决于从下拉列表中选择的项目? 让我说我从下拉列表中选择第一个元素,文本框最小值和最大值必须是2和4以及最大长度4.我在考虑使用RangeValidator和onChange事件?有任何解决方案/建议来实现这个目标吗?

编辑:这样的事情?

<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
<asp:TextBox ID="TextBox1" MaxLength="4" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Insert correct value."
MinimumValue="2" MaximumValue="4" Type="Integer"></asp:CompareValidator>

'CodeBehind
Populated dropdownlist.
DropDownList1.Attributes.Add("OnChange", "ChangeRangeValidatorValues();")

'Javascript function
        function indexChanged()
        {
            var textbox=document.getElementById('<%=TextBox1.ClientID%>');
            var droplist=document.getElementById('<%=DropDownList1.ClientID%>');
            var rangevalidator=document.getElementById('<%=RangeValidator1.ClientID%>');

        if (droplist.selectedIndex == 0)
        {
            textbox.maxLength=5;
            rangevalidator.minimumvalue=<%=ConfigurationManager.AppSettings["someValue"] %>;
            rangevalidator.maximumvalue=rangevalidator.minimumvalue;
        }else if (ddl.selectedIndex == 1){
            ..
        }else if (ddl.selectedIndex == 2) {
            ..
        }
    }

1 个答案:

答案 0 :(得分:2)

如果您使用的是c#asp.net,请使用此选项。如果有任何帮助评论,如果答案是有用的,请勾选答案以寻求帮助。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <script type="text/javascript">
       $(document).ready(function () {
           $('#DropDownList1').on('change', function () {
               var responseId = $(this).val();
               alert(responseId);

           $("#TextBox1").attr('maxlength', $(this).val());
       });
       });
   </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Text="2" Value="2" />
         <asp:ListItem Text="4" Value="4" />
        </asp:DropDownList>

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>


    </form>
</body>
</html>