How to limit the textarea to only hold numbers?
Asked Answered
L

8

12

I'm trying to make a date textbox on my blog, and the date is only numbers. I don't want anybody making a mistake typing a letter. Is there any way to limit the characters to only numerals? Thanks!

Lazo answered 22/3, 2014 at 0:38 Comment(1)
in html 5 there is a quick easy way ..<input type="number" /> will prevent from typing characters instead numbersOstracoderm
O
2

If you use jQuery, you can do it like in this jsfiddle

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();
});
Ostracoderm answered 22/3, 2014 at 0:56 Comment(0)
Z
12

Use HTML5 input number type instead and leverage native browser validation. Thus, no JavaScript required.

<input type="number" />

It has wide support in browsers and it's the standard and best-practice solution.

Also on mobile and tablets the numeric key pad will appear instead.

See demo

Zoarah answered 30/10, 2015 at 19:3 Comment(0)
O
8

you need some java script to implement this

<html>
<head>
<title>Test</title>
<script language="javascript">
function checkInput(ob) {
  var invalidChars = /[^0-9]/gi
  if(invalidChars.test(ob.value)) {
            ob.value = ob.value.replace(invalidChars,"");
      }
}
</script>
</head>

<body>
    <input type="text" onkeyup="checkInput(this)"/>
</body>
</html>
Ostracoderm answered 22/3, 2014 at 0:48 Comment(0)
M
2

Try this (utilizing jquery javascript library)

html

<input type="text" size="30" />

js (jquery library)

$(document).ready(function() {
    $("input").attr("placeholder", "Please input numbers").change(function(e) {
      var txt = /[a-z]/gi.test($(this).val());
      if (txt) {
        $(this).val("").attr("placeholder", "Not a number, please input numbers")
      };
    });
})

jsfiddle http://jsfiddle.net/guest271314/v2BRY/

Edit. Not certain if element is input ot textarea, hope should work for either.

javascript, without utilizing jquery javascript library

html

<input type="text" size="30" />

javascript

function checkText() {   
  var textarea = document.querySelectorAll("input");
  textarea[0].setAttribute("placeholder", "Please input numbers");    
  textarea[0].addEventListener("change", function(e) {
    var txt = /[a-z]/gi.test(e.target.value);
    if (txt) {
      e.target.value = "";
      e.target.setAttribute("placeholder", "Not a number, please input numbers");
    };    
  }, false);
};
checkText()

jsfiddle http://jsfiddle.net/guest271314/pFu4K/

Hope this helps

Manizales answered 22/3, 2014 at 0:54 Comment(3)
This answer assumes you are using jQueryKestrel
@Kestrel Edited post to include "utilizing jquery javascript library". jquery not needed to meet requirement, just sharing a potential option. Thanks.Manizales
@Kestrel Please see post edit option at "javascript, without utilizing jquery javascript library". Just sharing potential or possible options. Thanks, again.Manizales
O
2

If you use jQuery, you can do it like in this jsfiddle

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();
});
Ostracoderm answered 22/3, 2014 at 0:56 Comment(0)
L
1

Not sure if that was already available 8 years ago but the simplest way now to achieve what you want, if you want user to enter a date is:

<input type="date">
Lovett answered 8/9, 2022 at 21:11 Comment(0)
B
0

You should use this function to set input filters on various DOM elements including textarea

function setInputFilter(textbox, inputFilter) {
        ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
            textbox.addEventListener(event, function() {
                if (inputFilter(this.value)) {
                    this.oldValue = this.value;
                    this.oldSelectionStart = this.selectionStart;
                    this.oldSelectionEnd = this.selectionEnd;
                } else if (this.hasOwnProperty("oldValue")) {
                    this.value = this.oldValue;
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                } else {
                    this.value = "";
                }
            });
        });
    }

Then you simply set the filter, like that:

setInputFilter(document.getElementById("textarea_id"), value => {
        return /^\d*$/.test(value); // Allow digits and '.' only, using a RegExp
});
Bookcraft answered 31/3, 2020 at 12:23 Comment(0)
S
0

I know I'm late to the party but I'm writing this here as a reminder for myself in the future.

The html:

<textarea (oninput)="validateValue(event)"></textarea>

The JavaScript:

function validateValue(event){
  const elem = event.target;
  const value = elem.value;
  const numVal = value.replace(/\D/,"");
  elem.value = numVal;
}
Shalna answered 12/11, 2021 at 2:15 Comment(1)
The problem with using only /\D/ is if you use copy + paste. Then only the first character will be filtered. Use /\D+/g to solve this.Softboiled
S
0

I did not get the solution from @Morfinismo to work out of the box. However some small modifications did the trick.

<textarea oninput="validateValue(this)"></textarea>

<script>
    function validateValue(elem) {
        const value = elem.value;
        const numVal = value.replace(/\D+/g, "");
        elem.value = numVal;
    }
</script>

If you want to allow only numbers and new line character you can do it like this:

<textarea oninput="validateValue(this)"></textarea>

<script>
    function validateValue(elem) {
        const value = elem.value;
        const numVal = value.replace(/[^\d\n]+/g, "");
        elem.value = numVal;
    }
</script>
Softboiled answered 24/1, 2023 at 22:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.