>>> 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
Click here to see the jQuery function. It is alot easier if you are just looking for a function that accepts numbers to a textbox
The Code:
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
Click here to see the jQuery function. It is alot easier if you are just looking for a function that accepts numbers to a textbox
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
Advertisement by Google
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 =