动态添加/删除验证规则 [英] Add/remove validation rules Dynamically

查看:108
本文介绍了动态添加/删除验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击该行中的复选框时,我需要动态地将验证规则添加到文本框中,并在用户取消选中时将其删除。这就是我所做的,它工作正常,但我不确定这是否是正确的方法。
这是我的html代码:

I need to dynamically add validation rules to a text box when the user clicks on the checkbox in that row and remove it when the user unchecks it. This is what I did, and it works fine, but I'm not sure if it is the right way to do it. Here's my html code:

<tbody>
 <c:forEach items="${list}" var="item">
    <tr>
      <td align="center">
         <input type="checkbox" name="selectItems" value="<c:out value="${item.numberPlate}"/>" />
      </td>
      <td align="left"><c:out value="${item.numberPlate}"/></td>
      <td align="left"><c:out value="${item.driver.fullName}"/></td>
      <td align="left"><input type="text" name="mileage_<c:out value="${item.numberPlate}"/>" value="" /></td>
     </tr>
  </c:forEach>                       
</tbody>

和我的jquery:

-----已编辑----

现在我正在使用 add / removeClass ,它也可以正常工作,但是没有更快的方法吗?我的意思是,避免编写这么多'add / removeClass'指令的一种方法是什么?最后我怎么能用addClass表示min:100或minlength:6?

Now I'm using add/removeClass and it also works fine,but isn't there a quicker way of doing this? I mean , one way to avoid writing so many 'add/removeClass' instructions? and finally how could I indicate "min:100" or " minlength:6" with addClass?

$("input[name=selectItems]").change(function() {
    if (this.checked)
       {  
            $(this).closest("tr").find("input[name^=mileage]").addClass('required');
            $(this).closest("tr").find("input[name^=mileage]").addClass('number');
       }
     else
       {
            $(this).closest("tr").find("input[name^=mileage]").removeClass("required")
            $(this).closest("tr").find("input[name^=mileage]").removeClass('number');

       }
 });     

欢迎任何建议......我差点忘了,圣诞快乐!

any suggestion is welcome and... I almost forgot, Merry Xmas!

推荐答案

一个小改进是使用addClass和removeClass而不是使用attr分配类值,这样就不会删除任何已分配给不处理验证的输入字段的类(即分配给字段样式的类)

One small improvement would be to use addClass and removeClass instead of assigning class values using attr so that you would not remove any classes already assigned to the input fields that don't deal with validation (i.e. classes assigned to style the fields)

编辑: :(根据您的评论更新了以下代码)

: (Updated the code below as per your comments)

$("input[name=selectItems]").change(function() {
        var me = $(this);
        var scoper = me.parent().parent();
        var otherInputs = $("input[name^=mileage]", scoper);
    if (this.checked)
       {  
            otherInputs.addClass('required number');
            otherInputs.attr('maxlength', '6');
       }
     else
       {
            otherInputs.removeClass("required number");
       }
 });  

这篇关于动态添加/删除验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆