How to limit the textarea to only hold numbers?

后端 未结 6 634
自闭症患者
自闭症患者 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

    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
    });
    

提交回复
热议问题