Theodore Steiner Theodore Steiner - 2 months ago 8
CSS Question

Keeping Submit Button Disabled Until Form Fields Are Full

Would someone be able to take a look at my code and see what I'm missing here?

I have a multi-page form with quite a lot of inputs, and I would like to keep "next page" buttons and the final "submit" buttons disabled until all the fields are full.

I am trying to recreate the process on a smaller scale but in my tests, I cannot seem to re-enable the disabled submit input. I've checked the console and the JS is logging the variable elements so I'm not sure what I'm missing.



function checkForm()
{
var elements = document.forms[0].elements;

var cansubmit= true;

for(var i = 0; i < elements.length; i++)
{
if(elements[i].value.length == 0 || elements[i].value.length == "" || elements[i].value.length == null)
{
cansubmit = false;
}
document.getElementById("myButton").disabled = !cansubmit;
}

};

<form>
<label for="firstName">First Name:</label> <input type="text" id="firstName" onkeyup="checkForm()" />

<br />

<label for="lastName">Last Name:</label> <input type="text" id="lastName" onkeyup="checkForm()" />

<button type="button" id="myButton" disabled="disabled">Test me</button>
</form>




Answer

Your elements array includes your button, which has no value. This will cause your loop to always evaluate to cansubmit = false;.

Try this instead: https://jsfiddle.net/e00sorLu/2/

function checkForm()
{
    var elements = document.forms[0].elements;

    var cansubmit= true;
    for(var i = 0; i < elements.length; i++)
    {
        if(elements[i].value.length == 0 && elements[i].type != "button")
        {
            cansubmit = false;
        }

    }

    document.getElementById("myButton").disabled = !cansubmit;  
};