I have this input field: How can I allow only a number to be ...">

The maximum allowed value for <input type = "text" / ">

I have this input field:

<input type="text"/>

How can I allow only a number to be entered that does not exceed some predetermined value, for example, for example 10, so that every attempt to enter a number greater than 10 will not be allowed?

+2
source share
3 answers

Javascript

function createValidator(element) {
    return function() {
        var min = parseInt(element.getAttribute("min")) || 0;
        var max = parseInt(element.getAttribute("max")) || 0;

        var value = parseInt(element.value) || min;
        element.value = value; // make sure we got an int

        if (value < min) element.value = min;
        if (value > max) element.value = max;
    }
}

var elm = document.body.querySelector("input[type=number]");
elm.onkeyup = createValidator(elm);

HTML

<input type="number" min="0" max="10"></input>

I have not tested it, but I think it should work.

+4
source

Convert the value to a number immediately, and then compare it with the maximum value:

window.onload = function () {
    var textbox = document.getElementById("text1");
    var maxVal = 10;

    addEvent(textbox, "keyup", function () {
        var thisVal = +this.value;

        this.className = this.className.replace(" input-error ", "");
        if (isNaN(thisVal) || thisVal > maxVal) {
            this.className += " input-error ";
            // Invalid input
        }
    });
};

function addEvent(element, event, callback) {
    if (element.addEventListener) {
        element.addEventListener(event, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + event, callback);
    } else {
        element["on" + event] = callback;
    }
}

DEMO: http://jsfiddle.net/jBFHn/

, , "-" class. class .

+2

This is how I used this property in my project.

<script>
function integerInRange(value, min, max, name) {

    if(value < min || value > max)
    {
        document.getElementById(name).value = "100";
        alert("Write here your message");
    }
}
</script>

And my input like this

<input type="text" id="yyy" name="xxx" onkeyup="integerInRange(this.value, 0, 100, "yyy")" />

If you use bootstrap, you can use the warning window! function integerInRange (value, min, max, name) {

    if(value < min || value > max)
    {
        document.getElementById(name).value = "100";
        $.pnotify({ title: 'UYARI', text: 'Girilen değer ' + min + ' ile ' + max + ' arasında olmalıdır.', type: 'error' });
        $(".ui-pnotify-history-container").remove();
    }
}

0
source

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


All Articles