• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

8. Dynamic Forms > 8.11. Allowing Only Numbers (or Letters) in a Text Box

Allowing Only Numbers (or Letters) in a Text Box

NN 4, IE 4

Problem

You want to restrict a text field’s data entry to numbers only, letters only, or characters from a fixed set.

Solution

In IE 4 or later and Navigator 4 or later, you can allow onkeypress events to succeed only if the desired character keys are pressed. The following function, invoked from a text field’s onkeypress event, allows only numerals 0 through 9 (no decimals or minus signs):

function numeralsOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
        ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        alert("Enter numerals only in this field.");
        return false;
    }
    return true;
}

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint