views:

37

answers:

2
+1  Q: 

jQuery input value

We have some input elements on the page:

<input type="text" class="lovely-input" name="number" value="" />

User types a number he wants to see.

How to watch for this input value. with some options? They are:

  1. If user types a digit more than 100, change the value of input (on fly, without page refresh) to 100.
  2. If he types digit less than 1, turn value to 1.
A: 

The jquery validation plugin will handle your maximum and minimum value requirements.

In regard to changing input:

$("#number_input").change(function() {
  if($("#number_input").val() < 1) 
    $("#number_input").val(1);
});
jdc0589
this doesn't work
Happy
post your code, the concept is correct. You probably need to call parseInt in the val of the input element, and in some browsers the change event wont fire until the element looses focus.
jdc0589
should work straight when you type, not just on loosing focus
Happy
+1  A: 

Use the keyup event instead:

$(".lovely-input").keyup(function(e) {
    var $this = $(this);
    var val = $this.val();
    if (val > 100){
        e.preventDefault();
        $this.val(100);
    }
    else if (val < 1)
    {
        e.preventDefault();
        $this.val(1);
    }
});

Here's a working fiddle.

GenericTypeTea
whats doing preventDefault()?
Happy
It prevents the value of the last key hit from being entered.
GenericTypeTea
@GenericTypeTea seems preventDefault() doesn't work
Happy
Look at the link I gave under 'working fiddle'. It works fine. You're probably doing it wrong.
GenericTypeTea