How to limit a text field to numbers only?

I am trying to create a date text box on my blog, and the date is just numbers. I don’t want anyone to make a mistake typing a letter. Is there a way to limit characters to numbers only? Thank!

+4
source share
5 answers

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();
});
+3
source

you will need a 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>
+4
source

HTML5 . , JavaScript .

<input type="number" />

, .

mobile tablets .

.

+3

( javascript javascript library)

HTML

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

js ( jquery)

$(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/

. , element - input ot textarea, , .

javascript 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/

,

+1

, JavaScript. , JQuery , , . , , :

html to create a text field and not allow manual manipulation:

<input type="text" class="header_input" id="tvpostingdate" placeholder="Posting Date" default='' readonly="readonly">

a JS line linking the collector to a field with a specific format that my server process expects:

$('#tvpostingdate').datepicker({ dateFormat: "mmddyy"});

You can find more information here: http://jqueryui.com/datepicker/

-1
source

Source: https://habr.com/ru/post/1532933/


All Articles