2

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

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);
});

2 Comments

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.
should work straight when you type, not just on loosing focus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.