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>
Paolo
  • 20,112
  • 21
  • 72
  • 113
user1912654
  • 253
  • 1
  • 3
  • 5

9 Answers9

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I tried fiddling with this with no luck. Would you mind providing a jsfiddle? Thanks. – David Feb 04 '13 at 14:02
  • 1
    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. http://jsfiddle.net/6yPvg/3/ – Bergi Feb 04 '13 at 21:08
  • Bergi, thank you very much, especially for the explanation about onload. – David Feb 04 '13 at 22:44
  • One issue: it breaks with fieldsets. – David Feb 05 '13 at 02:16
  • How does what break with fieldsets? The loop over `elements`? – Bergi Feb 05 '13 at 07:20
  • Sorry to have been unclear. Wrapping the inputs in a fieldset breaks it. `
    `
    – David Feb 05 '13 at 13:37
  • 1
    Yeah, your `document.forms["theform"].elements` contains the `
    ` 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](http://jsfiddle.net/6yPvg/4/)).
    – Bergi Feb 05 '13 at 13:47
  • 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. – David Feb 05 '13 at 14:30
  • @David: Oops, I always think I'm discussing with the OP when someone has problems with a demo... – Bergi Feb 05 '13 at 17:19
  • @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. – Bergi Sep 05 '17 at 17:05
  • 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?? – sidoco May 23 '20 at 07:12
  • @sidoco I meant sending `` html instead of ``, so that the form starts usable. Then disable it by js (if js execution is enabled). – Bergi May 23 '20 at 08:15
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';
    }
}
Mario S
  • 11,715
  • 24
  • 39
  • 47
  • No. And don't (try to) set boolean properties to string values. – Bergi Dec 21 '12 at 13:51
  • 1
    @Bergi 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 ;) – Mario S Dec 21 '12 at 13:53
1

Put it inside a table and then do on her:

var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
dinafication
  • 301
  • 2
  • 10
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;
}
Community
  • 1
  • 1
jecz
  • 21
  • 1
  • 7
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

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
Vignesh A
  • 11
  • 3
  • 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 5 – Dilini Peiris Feb 09 '19 at 05:54
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>  
Zoe
  • 27,060
  • 21
  • 118
  • 148
M. Lak
  • 903
  • 9
  • 18
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);
                }
            } 
Edwinfad
  • 515
  • 6
  • 14
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>
deHaar
  • 17,687
  • 10
  • 38
  • 51
NIKHIL CHANDRA ROY
  • 807
  • 11
  • 16
0

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