Brie
Brie

Reputation: 2359

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?

Upvotes: 2

Views: 52

Answers (2)

Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9358

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.

Upvotes: 0

Miguel
Miguel

Reputation: 20633

Your regex does the following:

/. ./
  • matches any character (except newline)
  • matches the character literally
  • matches any character (except newline)

match method returns an array with results otherwise it returns null.

When there is no match your program is throwing an error because null does not have a length property. So the function throws an exception and the rest of the program within your script tag does not run.

One solution is to use test method which returns a boolean.

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

JSFiddle Demo: http://jsfiddle.net/vbgp6gba/2/

Upvotes: 1

Related Questions