【问题标题】:How to keep an element state unchanged forcefully如何强制保持元素状态不变
【发布时间】:2016-11-01 09:40:22
【问题描述】:

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

如果插件对正在观看的元素的验证失败,则当插件禁用提交按钮时,就会出现问题。

如何在不修改插件文件的情况下始终保持提交处于活动状态。但是,我将控制页面本身,因此我可以更改任何内容。

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

HTML

<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);
    }
});

【问题讨论】:

  • jsfiddle 没有引用插件。
  • 只需在插件后添加另一个事件处理程序...$(".adv-form-field").on("blur", function() { $("#submit").prop("disabled", false); });
  • @user2181397 这是一个 vBulletin 论坛,不可能包含它。但它做了很多检查,然后是启用/禁用按钮。
  • @Archer 该插件在页面加载时也将其设置为禁用状态,既然您提到了这一点,我应该也可以为加载添加一个事件处理程序。我会更新你的进展。谢谢
  • 应该可以解决你的问题,是的。只要在插件初始化后分配 2 个新的事件处理程序,它们就应该有效地覆盖您不希望看到的行为。

标签: javascript jquery validation disabled-input


【解决方案1】:

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

如果你添加它,它将在 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);
});

【讨论】:

    【解决方案2】:

    我不知道您使用的是哪个插件,但根据我之前使用表单验证插件的经验,而不是输入 &lt;button id="submit"&gt;Submit&lt;/button&gt; 使用:

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

    【讨论】:

    • 这是我写的一个例子来说明正在发生的事情。该插件将input:submit 的禁用状态设置为true。
    猜你喜欢
    • 2016-10-19
    • 2021-10-30
    • 1970-01-01
    • 2021-07-22
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2015-09-21
    相关资源
    最近更新 更多