user1699085
user1699085

Reputation:

javascript, limit number of characters in text field

I have a form which allows only for numbers to be entered in the text box, or an alert appears:

<form name="formName" action="" method="post" OnSubmit="return chkSubmit();"> 
    Input Number 
    <input type="text" name="txtNumber" value="">
    <input type="submit" name="btnSubmit" value="Submit">
</form>

with the following javascript:

<script>
function chkSubmit()
{
     if(isNaN(document.formName.txtNumber.value))
     {
        alert('Please input numbers only.');
        return false;
     }
}</script>

How do I allow for only 4 characters to be entered? No alert, just prevent the user from typing more than 4 characters.

Upvotes: 2

Views: 9027

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075915

input elements support a maxlength attribute, e.g.:

<input type="text" name="txtNumber" value="" maxlength="4">

...which is then enforced by the user agent (browser). You can also enforce it in your chkSubmit if you want a belt-and-braces approach, by checking the length of the value property, but it's been around forever and I doubt you'll find a user agent that doesn't handle it.

RobG's point (in a comment on the question) is well-taken, as well: Restricting users prior to form submission tends to be irritating for them. It may or may not be appropriate for your use-case, but at least consider not limiting them (but perhaps giving some visual feedback using the keypress event), and only validating length on submit, the way Stack Overflow does on comments.

Upvotes: 5

Phil
Phil

Reputation: 473

Use maxlength

<form name="formName" action="" method="post" OnSubmit="return chkSubmit();"> 
    <input type="text" name="txtNumber" maxlength="4" value="" />
    <input type="submit" name="btnSubmit" value="Submit" />
</form>

Upvotes: 1

Related Questions