I got this code:
var $this = $(this);
var val = $this.val();
var max = $this.attr("max");
var min = $this.attr("min");
if (max > 0 && val > max){
e.preventDefault();
$this.val(max);
}
else if (min > 0 && val < min)
{
e.preventDefault();
$this.val(min);
}
The problem is for instance when min/max
are 70/250
and the user try to type 200
it gets instantly corrected from 2
to 70
-_- so I need timeout/delay on keyup
so I tried:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$("input").keyup(function(e) {
delay(function(){
var $this = $(this);
var val = $this.val();
var max = $this.attr("max");
var min = $this.attr("min");
if (max > 0 && val > max){
e.preventDefault();
$this.val(max);
}
else if (min > 0 && val < min)
{
e.preventDefault();
$this.val(min);
}
}, 1000 );
});
But now the correction isn't getting executed. How to do it right? Does anyone also have a btter idea to solve the "typing 200 without getting instantly corrected" problem?
你正在寻找的是'去抖':你可能想要修补这个解决方案: https : //davidwalsh.name/javascript-debounce-function
You could use the Jquery focusout function.
https://www.w3schools.com/jquery/event_focusout.asp
This will check when the user moves to another field or input section and will then perform your validation. No need then for timers or delays.
$("input").focusout(function(e) {
var $this = $(this);
var val = $this.val();
var max = $this.attr("max");
var min = $this.attr("min");
if (max > 0 && val > max){
e.preventDefault();
$this.val(max);
}
else if (min > 0 && val < min)
{
e.preventDefault();
$this.val(min);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.