pacerier — 2010-08-23T15:14:34-04:00 — #1
heys all, i'm trying to restrict user input to only 3 digits (3 numbers iow)
so what i've did is to check the onkeydown and check if they are digits and if input.value text length is 3 or more i will cancel it.
However, if the user had words selected in the textbox, i will wish to allow input. Because imagine the user selected the string "123" in the textbox, and wishes to override this string by typing a new number. but with my current logic, since the textbox already have 3 digits, he had his input rejected, which is not what i would want.
is there a workaround?
pacerier — 2010-09-03T02:35:12-04:00 — #2
hey thanks for the reply. i may need this in the future for other more complex requirements
raffles — 2010-08-23T15:22:13-04:00 — #3
Why don't you just use the maxlength attribute?
<input type="text" maxlength="3">
raffles — 2010-08-23T20:03:47-04:00 — #4
Yes, there is, but it's complex because IE and decent browsers have different ways of going about it. In Firefox, Safari and Opera it would be very simple:
var selectedText = inp.selectionEnd - inp.selectionStart > 0;
where inp is a reference to the text box. The selectedText var would be true or false, indicating if text was selected. IE requires you to use document.selection and follow a roundabout way of finding the length of the selected text.
But from what you describe, it seems like maxlength will do what you want.
pacerier — 2010-08-23T18:13:54-04:00 — #5
lol i've forgotten about that.
but other than that, there is no way to check if text has been selected within the textbox right?