Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep value in html input box below set amount

I have in input box that can only contain numerical values (with use of this plugin).
Now I want the input to be below, say 90. If a value is entered that exceeds this max cap or cannot be parsed, the previous value should be inserted. By default, the box will contain "1".

<input id="targetQuantity" name="targetQuantity" type="text" value="1" />

I imagine I should catch the current value somehow. Try to parse the new value. If it is an allowed value, continue with this value, if not, put the old one back.
As my JS skills are really limited I don't even know what events are available to me and I find the documentation I found on the intarwebz rather confusing.

--EDIT--
I ended up using Sergei's code and using Aaron's usability advice.
All I'm looking for now is to enable/disable a whole form's submit. Just disabling a submit button is not enough.

like image 513
Boris Callens Avatar asked Mar 10 '09 13:03

Boris Callens


People also ask

How do I restrict a number in a text box in HTML?

You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

How do you assign a value to an input field in HTML?

The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button. For "text", "password", and "hidden" - it defines the initial (default) value of the input field.

How do you set limits in input type text?

To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.


1 Answers

<input id="targetQuantity" name="targetQuantity" type="text" value="1" onkeyup="check(this)" />

... JavaScript:

var v=1;

function check(i) {      
  if(i.value > 100) {
    i.value=v;
    alert("< 100");
  }
  else
    v=i.value;
}
like image 80
Sergei Avatar answered Nov 08 '22 20:11

Sergei