How to limit the textarea to only hold numbers?

后端 未结 6 730
自闭症患者
自闭症患者 2021-01-18 11: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

6条回答
  •  没有蜡笔的小新
    2021-01-18 11:27

    Try this (utilizing jquery javascript library)

    html

    
    

    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

    
    

    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

提交回复
热议问题