如何禁用CSS验证边框

时间:2018-08-29 14:52:42

标签: jquery css

我正在开发一个JQuery函数,该函数将在填充第二个字段而事实相反时禁用TextBox字段。

换句话说,它将输入限制为一个字段。

当我用长角形文字测试两个字段中的一个(输入仅限于数字)中的一个,然后再次将其设为空并转到该字段时,在第一个字段周围仍显示红色边框的问题尽管它已被禁用。

我试图删除规则,但是没有用。

代码:

 $("#FirstId").on('input', function () {
        if ($(this).val() != "") {
            $('#SecondId').prop("disabled", true);
        }
        else {
            $('#SecondId').prop("disabled", false);

        }
    })

    $("#SecondId").on('input', function() {
        if ($(this).val() != "") {
            $('#FirstId').prop("disabled", true);
        }
        else {
            $('#FirstId').prop("disabled", false);
        }
    })

    $("#SecondId").on('input', function ClearValidation() {

            $('#FirstId').rules('remove');

    })

2 个答案:

答案 0 :(得分:2)

这就是您想要的样子吗?如果您不想在禁用红色边框时禁用它,只需在禁用该输入时删除无效的类

$("#FirstId").on('input', function () {
        if ($(this).val() != "") {
        $("#FirstId").removeClass("disabled");
        $("#SecondId").removeClass("invalid");
            $('#SecondId').prop("disabled", true);
        }
        else {
            $('#SecondId').prop("disabled", false);
        }
        
        if ($(this).val() == "") {
          $("#FirstId").addClass("invalid");
        } else {
          $("#FirstId").removeClass("invalid");
        }
    })

    $("#SecondId").on('input', function() {
        if ($(this).val() != "") {
        $("#FirstId").removeClass("invalid");
            $('#FirstId').prop("disabled", true);
        }
        else {
        
            $('#FirstId').prop("disabled", false);
        }
        
        if ($(this).val() == "") {
          $("#SecondId").addClass("invalid");
        } else {
          $("#SecondId").removeClass("invalid");
        }
    })

  
.invalid{
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" id="FirstId">
<input type="number" id="SecondId">

答案 1 :(得分:1)

由于您要删除的rules,我假设您使用jQuery-Validate插件...您应该已经提到了插件的用法。

我做了一些可能与您在标记方面相近的事情...而且我大大地“减少了”您的代码。看看:

var first = $('#FirstId');
var second = $('#SecondId');

first.on('input', function () {
  // Enable/disable the other input
  second.prop("disabled", $(this).val() != "");
});

second.on('input', function() {
  // Enable/disable the other input
  first.prop("disabled", $(this).val() != "");
  // Remove validation error
  first.removeClass('error');
  first.next("label.error").remove();
});

$("#myForm").validate({
  rules:{
    FirstId: "number"
  }
});
input.error{
  border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

<form id="myForm">
  <input id="FirstId" name="FirstId" required><br>
  <input id="SecondId" name="SecondId" required><br>
</form>

因此,在#FirstId中键入一个字母...然后将其删除。它将显示有关“必需”的错误消息。然后输入#SecondId。以前的错误现已删除。