[javascript] Disable/Enable Submit Button until all forms have been filled

I want my form submit button to be disabled/enabled depending on if the form is completely filled.

When the inputs are filled, the disabled button changes to enabled. That works great. But I would like it to disable the button when an input gets emtied.

This is my script:

<script type="text/javascript" language="javascript">
    function checkform()
    {
        var f = document.forms["theform"].elements;
        var cansubmit = true;

        for (var i = 0; i < f.length; i++) {
            if (f[i].value.length == 0) cansubmit = false;
        }

        if (cansubmit) {
            document.getElementById('submitbutton').disabled = false;
        }
    }
</script> 
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>

This question is related to javascript forms submit disabled-control

The answer is


Just add an else then:

function checkform()
{
    var f = document.forms["theform"].elements;
    var cansubmit = true;

    for (var i = 0; i < f.length; i++) {
        if (f[i].value.length == 0) cansubmit = false;
    }

    if (cansubmit) {
        document.getElementById('submitbutton').disabled = false;
    }
    else {
        document.getElementById('submitbutton').disabled = 'disabled';
    }
}

<form name="theform">
    <input type="text" />
    <input type="text" />`enter code here`
    <input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>

<script type="text/javascript" language="javascript">

    let txt = document.querySelectorAll('[type="text"]');
    for (let i = 0; i < txt.length; i++) {
        txt[i].oninput = () => {
            if (!(txt[0].value == '') && !(txt[1].value == '')) {
                submitbutton.removeAttribute('disabled')
            }
        }
    }
</script>

Put it inside a table and then do on her:

var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);

Here is my way of validating a form with a disabled button. Check out the snippet below:

_x000D_
_x000D_
var inp = document.getElementsByTagName("input");_x000D_
var btn = document.getElementById("btn");_x000D_
// Disable the button dynamically using javascript_x000D_
btn.disabled = "disabled";_x000D_
_x000D_
function checkForm() {_x000D_
    for (var i = 0; i < inp.length; i++) {_x000D_
        if (inp[i].checkValidity() == false) {_x000D_
            btn.disabled = "disabled";_x000D_
        } else {_x000D_
            btn.disabled = false;_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8"/>_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>_x000D_
    <title>JavaScript</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<h1>Javascript form validation</h1>_x000D_
<p>Javascript constraint form validation example:</p>_x000D_
_x000D_
<form onkeyup="checkForm()" autocomplete="off" novalidate>_x000D_
    <input type="text" name="fname" placeholder="First Name" required><br><br>_x000D_
    <input type="text" name="lname" placeholder="Last Name" required><br><br>_x000D_
    <button type="submit" id="btn">Submit</button>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Example explained:

  1. We create a variable to store all the input elements.
    var inp = document.getElementsByTagName("input");
    
  2. We create another variable to store the button element
    var btn = document.getElementById("btn");
    
  3. We loop over the collection of input elements
    for (var i = 0; i < inp.length; i++) {
        // Code
    }
    
  4. Finally, We use the checkValidity() method to check if the input elements (with a required attribute) are valid or not (Code is inserted inside the for loop). If it is invalid, then the button will remain disabled, else the attribute is removed.
    for (var i = 0; i < inp.length; i++) {
        if (inp[i].checkValidity() == false) {
            btn.disabled = "disabled";
        } else {
            btn.disabled = false;
        }
    }
    

Here is the code

<html>
   <body>
      <input type="text" name="name" id="name" required="required"                                    aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
      <script>
       function func()
       {
        var namdata=document.form1.name.value;
         if(namdata.match("[a-z]{1,5}"))
        {
         document.getElementById("but1").disabled=false;
        }
        }
        </script>
  </body>
</html>

Using Javascript


I just posted this on Disable Submit button until Input fields filled in. Works for me.

Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.

http://www.w3schools.com/jsref/event_form_onsubmit.asp

<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
   ...
</form>

function validateCreditCardForm(){
    var result = false;
    if (($('#billing-cc-exp').val().length > 0) &&
        ($('#billing-cvv').val().length  > 0) &&
        ($('#billing-cc-number').val().length > 0)) {
            result = true;
    }
    return result;
}

You can enable and disable the submit button based on the javascript validation below is the validation code. Working Example Here

<script>
function validate() {

var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));

$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
} 
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html(""); 
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}

return true; 
}
function checkEmail(obj) {
var result = true;

var name = $(obj).attr("name");
$("."+name+"-validation").html(""); 
$(obj).css("border","");

result = checkEmpty(obj);

if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}

var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());

if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}

return result; 
}
</script>  

I think this will be much simpler for beginners in JavaScript

    //The function checks if the password and confirm password match
    // Then disables the submit button for mismatch but enables if they match
            function checkPass()
            {
                //Store the password field objects into variables ...
                var pass1 = document.getElementById("register-password");
                var pass2 = document.getElementById("confirm-password");
                //Store the Confimation Message Object ...
                var message = document.getElementById('confirmMessage');
                //Set the colors we will be using ...
                var goodColor = "#66cc66";
                var badColor = "#ff6666";
                //Compare the values in the password field 
                //and the confirmation field
                if(pass1.value == pass2.value){
                    //The passwords match. 
                    //Set the color to the good color and inform
                    //the user that they have entered the correct password 
                    pass2.style.backgroundColor = goodColor;
                    message.style.color = goodColor;
                    message.innerHTML = "Passwords Match!"
 //Enables the submit button when there's no mismatch                   
                    var tabPom = document.getElementById("btnSignUp");
                    $(tabPom ).prop('disabled', false);
                }else{
                    //The passwords do not match.
                    //Set the color to the bad color and
                    //notify the user.
                    pass2.style.backgroundColor = badColor;
                    message.style.color = badColor;
                    message.innerHTML = "Passwords Do Not Match!"
 //Disables the submit button when there's mismatch       
                    var tabPom = document.getElementById("btnSignUp");
                    $(tabPom ).prop('disabled', true);
                }
            } 

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to submit

React - clearing an input value after form submit angular2 submit form by pressing enter without submit button spark submit add multiple jars in classpath jQuery's .on() method combined with the submit event Selenium Webdriver submit() vs click() PHP form - on submit stay on same page Disable submit button ONLY after submit HTML - How to do a Confirmation popup to a Submit button and then send the request? HTML form with multiple "actions" Javascript change color of text and background to input value

Examples related to disabled-control

Disable submit button when form invalid with AngularJS Disable/Enable Submit Button until all forms have been filled asp:TextBox ReadOnly=true or Enabled=false?