如何强制保持元素状态不变

How to keep an element state unchanged forcefully

本文关键字:状态 元素 何强制      更新时间:2023-09-26

我有一个行为正常的表单,输入通过简单的验证进行验证。我们安装了一个插件,它提供一些深入的验证。

当插件禁用提交按钮时,如果它对它正在监视的元素的验证失败,问题就出现了。

如何在不修改插件文件的情况下始终保持提交处于活动状态?但是,我可以控制页面本身,所以我可以修改任何东西。

我创建了一个简单的JSFiddle来说明这种情况:JSFiddle

<form action="#" id="form">
  Name: <input type="text" id="name" class="form-field">
  <span class='error-message'>Name is required</span><br>
  Age: <input type="text" id="age" class="form-field">
  <span class='error-message'>Age is required</span><br>
  Password: <input type="password" id="pass" class="adv-form-field">
  <span class='error-message'>Advanced messages</span>
  <button id="submit">Submit</button>
</form>
CSS

.error-message{
  display: none;
}

JavaScript (jQuery)

// Simple validation to check if the fields have values
$(".form-field").on("blur", function(){
        if(this.value == ""){
        $(this).next(".error-message").css("display", "block");
    } else {
         $(this).next(".error-message").css("display", "none");
    }
});

// Suppose this is the advanced function | we will have no control over this
$("#submit").prop("disabled", true);
$(".adv-form-field").on("blur", function(){
        if(this.value == ""){
        $(this).next(".error-message").css("display", "block");
      $("#submit").prop("disabled", true);
    } else {
         $(this).next(".error-message").css("display", "none");
       $("#submit").prop("disabled", false);
    }
});

你可以在插件初始化后添加你自己的事件处理程序,这些将有效地覆盖(而不是真正覆盖)插件的事件处理程序…

如果你添加了这个,它将运行在document.ready…

$(function() {
    // set submit button enabled after input field blur
    $(".adv-form-field").on("blur", function() {
        $("#submit").prop("disabled", false);
    });
    // set initial state of submit button
    $("#submit").prop("disabled", false);
});

我不知道你使用的是哪个插件,但从我以前使用表单验证插件而不是输入<button id="submit">Submit</button>的经验来看:

<input type="submit" id="submit">