Possible Duplicate:
How to impose maxlength on textArea in HTML using JavaScript
I have a grid of buttons where the user selects a button. Lets ignore buttons “True or False” and “Yes or No”, the other buttons go from “3” to “26”. Now there is a text-box (#numberAnswerTxt), where the user can select the number of answers the user wants. Now what I want to do is that the user cannot type in a number in the text-box which is more than the number of options from the button.
So for example if the user select button “3” from the grid, then in the text-box the user can only type in the number 3 as the maximum number in the text-box, if the user types in a higher number then the text-box should automatically change the number to the highest number which is “3”.
Another example is that if the user select button “21” from the grid, then in the text-box the user can only type in the number 21 as the maximum number in the text-box, if the user types in a higher number then the text-box should automatically change the number to the highest number which is “21”.
Does anyone know how to do this?
The code is in jsfiddle, click here
Thank You
Something like this should do it:
On change it will take the minimum value from what was typed and what was in the other field. The change event is triggered when you leave (tab or click out of) the field. If you want it to happen as the user types use
keyup()instead ofchange().Demo: http://jsfiddle.net/aMmNL/1/
You may want to add some validation that the value entered is actually a number. My code above uses the unary + operator to convert the string values to numbers, which isn’t really necessary because (I’m pretty sure) the Math.min function converts for you, but note that it will return NaN if one of the values can’t be converted.
NOTE: your jsfiddle has a document ready handler nested inside another document ready handler:
Although it works to have more than one there’s not much point unless they’re in separate JS files, and there’s no point in nesting them.