Textareas are commonly used in web forms to allow users to enter multi-line text input. By default, textareas allow users to enter any character they want, including letters, numbers, symbols, and line breaks. However, in some cases, you may want to restrict the input to only numbers and line breaks. This can be achieved using JavaScript.
Here is a script in JavaScript that allows you to remove any unwanted text character other than new lines and numeric keywords. This can be used in places where textarea needs to exclude anything other than numbers and newlines.
Here is the HTML code to create a simple textarea:
<textarea id="nos"></textarea>
And here is the JavaScript code to restrict the input to only numbers and line breaks:
document.getElementById('nos').addEventListener("keyup", function(){
var invalidChars = /[^0-9\n]/gi;
if(invalidChars.test(this.value)) {
this.value = this.value.replace(invalidChars,"");
}
});
See the Pen Untitled by Puneet Sharma (@webdevpuneet) on CodePen.