I have text boxes <input type='text'>
that only allow numeric characters and wont let the user enter a dot (.) more than once. Problem is, if the text in the text box is selected, the user intends to overwrite the contents with a dot, hence making it allowed! The question is, how can you tell in javascript whether the text in that text box is selected or not.
Thanks
Instead of hitting the wall of digits dots and selections you can climb it easily by checking the value in
onchange
event.HTML:
JS:
This will check the value when changed (and user go to different element) and when not valid will alert and set focus back.
Live test case: http://jsfiddle.net/yahavbr/NFhay/
You can get the id of the selected element in the page with the following code:
The following will tell you whether or not all of the text is selected within a text input in all major browsers.
Example: http://www.jsfiddle.net/9Q23E/
Code:
For anyone who needs the code to get at the selected text within a textbox, here's an enhanced version:
http://jsfiddle.net/9Q23E/527/
2017 Specific Answer - Faced the same issue recently.
We were allowing users to enter only 3 digits at a time. When the user tried to enter the fourth character we returned false.
This became an issue when the user had a selection and was trying to overwrite the values.
Taking a hint from Tim's answer. I understood that I wanted to see if the
selection value
was same as theinput's value
.In modern browsers I achieved it by doing:
Hope this helps someone.