Reputation: 937
I have this input field:
<input type="text"/>
How can I allow entering only a number that is not greater than some predefined value, like for example 10, so every attempt to enter a number greater than 10 won't be allowed?
Upvotes: 3
Views: 24709
Reputation: 840
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 using bootstrap you can use alert 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();
}
}
Upvotes: 0
Reputation: 27205
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 haven't tested it, but I think it should work.
Upvotes: 7
Reputation: 50905
Convert the value to a number immediately, then compare it to a 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/
As you type, if the value isn't a number or the value is greater than the maximum, the "input-error" class
is added to the element. You can take out the whole class
changing, and put in your own stuff.
Upvotes: 3