Search code examples
javascripthtmlformsdisabled-controlsubmit-button

Cannot re-set form submit button to disabled


On a webpage I have a form:

<form action="/SignUp.py" method="post">
    <input required type="text" name="fullName" onKeyPress="checkFinished()" autofocus>
    <input type="submit" name="submitButton" value="Sign Up" disabled>
</form>

and script:

<script>
    function checkFinished() {
        if (document.getElementsByName("fullName")[0].value.match(/. ./).length > 0) {
            document.getElementsByName("submitButton")[0].disabled = false;
        }
        else {
            document.getElementsByName("submitButton")[0].disabled = true;
        }
    }
</script>

If I step through the code using Firebug, I can see the execution path is correct. However, when the code hits the else clause and should be (re-)disabling submitButton, it does not get disabled. What am I doing wrong here?


Solution

  • I made a little fiddle for you to take a look at

    https://jsfiddle.net/mo5wfjLt/2/

    What is wrong in your code :

    First of all, backspace is not triggering a keypress event, so you will have a problem there in case you want to delete characters. Use keyup instead. If you want to experiment with key events, try this out: http://www.asquare.net/javascript/tests/KeyCode.html

    The next major error is this line

    document.getElementsByName("fullName")[0].value.match(/. ./).length
    

    If a document.getElementsByName("fullName")[0].value.match(/. ./) does not exist, this returns null, so when you immediately try to access .length on that, you are trying to do null.length, so you get an Uncaught TypeError: Cannot read property 'length' of null

    Also it's a good practice to keep values such as document.getElementsByName("fullName")[0], for example, in variables. It helps.

    So, check the fiddle, and if there is something you still don't understand, ask.