Disable/Enable Submit Button until all forms have been filled
Asked Answered
A

9

25

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>
Assured answered 18/12, 2012 at 11:12 Comment(0)
M
26

Just use

document.getElementById('submitbutton').disabled = !cansubmit;

instead of the the if-clause that works only one-way.

Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.

Mahla answered 21/12, 2012 at 13:48 Comment(12)
I tried fiddling with this with no luck. Would you mind providing a jsfiddle? Thanks.Feudal
No if-statement, I said. Also, if you configure jsfiddle to execute your script onload, function and variable declarations will be local to an anonymous function and not accessible from inline handlers. Use the no-wrap option. jsfiddle.net/6yPvg/3Mahla
Bergi, thank you very much, especially for the explanation about onload.Feudal
One issue: it breaks with fieldsets.Feudal
How does what break with fieldsets? The loop over elements?Mahla
Sorry to have been unclear. Wrapping the inputs in a fieldset breaks it. <form name="theform"> <fieldset> <input type="text" onKeyup="checkform()" /> <input type="text" onKeyup="checkform()" /> <input id="submitbutton" type="submit" disabled="disabled" value="Submit" /> </fieldset> </form>Feudal
Yeah, your document.forms["theform"].elements contains the <fieldset> element which has no value property. You will need to specify your elements list better, or test the f[i] for being a text input (simple fix).Mahla
Bergi, if it had been my question, then I would have accepted it. I did upvote your answer. Sorry I can't do more. & thanks for the fix.Feudal
@David: Oops, I always think I'm discussing with the OP when someone has problems with a demo...Mahla
@jEXEy You are totally correct that this should be done with the required attribute. Please don't hijack my answer though, rather post your own.Mahla
Hi , I dont uderstand this : Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. when JS was disabled, how set initial by JS? Do you mean java on server??Algo
@Algo I meant sending <input type=submit> html instead of <input type=submit disabled>, so that the form starts usable. Then disable it by js (if js execution is enabled).Mahla
V
2

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';
    }
}
Vespasian answered 21/12, 2012 at 13:48 Comment(2)
No. And don't (try to) set boolean properties to string values.Mahla
@Mahla I'm just extending the OP's code. If you want to tell the OP not to use boolean values on string properties, then I suggest adding a comment to the question and not my answer ;)Vespasian
F
1

Put it inside a table and then do on her:

var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
Flitch answered 4/11, 2013 at 12:49 Comment(1)
Need jQuery for this.Burke
B
1

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;
}
Babbling answered 24/11, 2013 at 21:21 Comment(0)
E
1

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

Elinaelinor answered 23/3, 2017 at 5:18 Comment(1)
Just using the required attribute is enough right? Because if a required field is not filled the action in the submit button does not execute. It tells the user the fill the required field. This is a new feature in HTML 5Yielding
R
1

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

var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";

function checkForm() {
    for (var i = 0; i < inp.length; i++) {
        if (inp[i].checkValidity() == false) {
            btn.disabled = "disabled";
        } else {
            btn.disabled = false;
        }
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>JavaScript</title>
</head>
<body>

<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>

<form onkeyup="checkForm()" autocomplete="off" novalidate>
    <input type="text" name="fname" placeholder="First Name" required><br><br>
    <input type="text" name="lname" placeholder="Last Name" required><br><br>
    <button type="submit" id="btn">Submit</button>
</form>

</body>
</html>

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;
        }
    }
    
Revolutionist answered 7/5, 2020 at 10:11 Comment(0)
M
0

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

<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>  
Mercator answered 20/3, 2018 at 11:59 Comment(0)
G
0

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);
                }
            } 
Ghiberti answered 25/3, 2018 at 4:11 Comment(0)
A
0
<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>
Append answered 9/12, 2019 at 10:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.