views:

1211

answers:

3

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.

+1  A: 

This should help: JavaScript Madness: Keyboard Events

Now a word on usability: Never ever change the value as the user types. If you want to know why, try it.

Instead, turn the field red (set the background color). When the form is submitted, run the validation again to make sure the user has fixed the mistake. If not, display an inline error message ("value must be < 90") somewhere near the field and set the focus to the field.

Do not use alert(). alert() is for debugging only and has no use in a real web application since it a) interrupts the work flow of the user and b) doesn't work when the user is typing: Eventually, the user will hit space and the dialog will close, possibly with the user ever noticing that there was a dialog or what it said.

You may want to check out a library like jQuery or Prototype because they already contain all the building blocks you need and they fix a lot of the browser bugs for you.

Aaron Digulla
Thanks for the advice. I don't use alerts except for debugging. In fact, they are the reason why I surf without script in Opera most of the time. Also, I'm already using JQuery.
borisCallens
+1  A: 
<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;
}
Sergei
A: 

write this js in a javascript code block:

var LastGood = 1;
function CheckValue(input, max) {
    var value = Number(input.value);
    if (NaN == value || input.value>max) { //it is not a number or is too big - revert
        input.value = LastGood;
    } else { //it is ok, save it as the last good value
        LastGood = value;
    }
}

change your input form to

<input id="targetQuantity" name="targetQuantity" type="text" value="1" onkeyup="CheckValue(this, 90)" />
Spikolynn