379714 visitors has seen the Tim-Carter.com site. Thanks!
319 visitors has seen the Tim-Carter.com site today.
 
 
Search :  
 
>>> Programming >> Javascript > Make an input text field only accept certain chars (This page has been seen 1876 times)

Make an input text field only accept certain chars

Below is a function that will take a regular expression and execute it on a input text box.

If you add onkeyup='filter(this,5,"[^0-9]");' to the input text tag. then it will only allow numbers from 0-9 and a length on the string of only 5 chars


The Code:
function filter(element, length, regex) {
    /*USAGE
    ACCEPT ONLY NUMBERS AND LENGTH IF 5
    onkeyup='filter(this,5,"[^0-9]");'
    */
    var id = element.id;
    var val = element.value;
    var regex = new RegExp(regex, "gi");
    var allowed = length;
    val = val.replace(regex, '');
    val = val.substring(0, allowed);
    document.getElementById(id).value = val;
};

Like (20)
 
Dislike (7)


Keywords for this article:
filter input text || allow only numbers in text box

Post comment

Name:


Comment:

Code Language:

Code:

Here you can paste a code example. It will then be processed by SyntaxHighlighter and formatted for easier readability.
Please remember to select the correct Code Language in the select above so the SyntaxHighlighter can highlight the code properly.




Code:

Please enter the code you see above

What is 10 + 10 =

Submit Comment


No one has commented on this page yet. You could be the first.


Advertisement by Google


Sponsors :