0

I have an text input for pagination page changing. I need to limit typing of page numbers to some number f.e. 15 (max pages number). So i'm trying with this code below but always when number is higher than 15 value is changing to 15 and actual typing number.

actual.on('keypress', function() {
    console.log('test');
    var t = $(this);
    if (t.val() < 1) t.val('1');
    if (t.val() > 15) t.val('15');
});

Fiddle: http://jsfiddle.net/v6fhobr7/

Can anybody help?

Lukas
  • 7,384
  • 20
  • 72
  • 127

4 Answers4

6

Try changing it from 'keypress' to 'keyup' ... there's a slight flicker, but it works.

rfornal
  • 5,072
  • 5
  • 30
  • 42
1

Use a number field.

<input type="number" min="1" max="15" step="1">
Evan Davis
  • 35,493
  • 6
  • 50
  • 57
  • It doesn't rewrite the value for you, but it limits the set of valid responses. – Evan Davis Dec 03 '14 at 00:19
  • This is a very elegant solution, but is not supported in all browsers (such as mobile browsers or IE < 10). http://caniuse.com/#feat=input-number – AJ Richardson Dec 03 '14 at 00:19
  • It's a solution for your problem, but not a solution for your solution. "How do I limit input to a field" is a solution to the problem "how do I only accept valid responses." But I digress. @aj_r is correct; I thought this feature was more widely supported than it is. – Evan Davis Dec 03 '14 at 00:22
0

@rfornal's solution works okay, but it's hard to type single digit value unless you're really fast:

http://jsfiddle.net/v6fhobr7/7/

So it's better to set a slight timeout before changing the value:

var actual = $('.actual');
var tm;

actual.on('keyup', function () {
    var t = $(this);

    if (tm) clearTimeout(tm);
    tm = setTimeout(function() {
        if (t.val() < 1) t.val('1');
        if (t.val() > 15) t.val('15');
    }, 250);
});

JSFiddle demo: http://jsfiddle.net/v6fhobr7/10/

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
  • hmmm, i don't have this issue with single digit, everything is works correctly, but thx – Lukas Dec 03 '14 at 00:19
0

In jQuery 2.x, you can use actual.on('input'), which does what you want without the flicker.

Note that this will prevent the user from clearing out the input entirely; if you want to allow this then you might want to handle the case where t.val() == '' explicitly.

actual.on('input', function(e) {
    var t = $(this);
    if (t.val() == '') return;
    if (t.val() < 1) t.val('1');
    if (t.val() > 15) t.val('15');
});

http://jsfiddle.net/v6fhobr7/12/

Edit:

Note that this solution doesn't restrict input to only numeric characters (you can still type letters and symbols). If you want to prevent that, use this solution in addition to my answer above.

Or, if you don't care about IE 9 or mobile browsers, Mathletics's answer is the best.

Community
  • 1
  • 1
AJ Richardson
  • 6,610
  • 1
  • 49
  • 59