ISuthan Bala ISuthan Bala - 5 months ago 22
Javascript Question

How to keep an element state unchanged forcefully

I have a form which behaves normally, with the inputs validated by simple validation. We installed a plugin, which provides some in-depth validation.

The issue arises when the plugin disables the submit button if it's validation fails on the elements it's watching.

How can I keep the submit on active state at all time without making any modification to the plugin files. However, I will have control on the page itself, so I can alter anything.

A simple JSFiddle I created to illustrate the situation:
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);
}
});

Answer

You can add your own event handlers after the plugin has initialised, and these will effectively override (not actually override) the plugin event handlers...

If you add this it will run on 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);
});
Comments