53

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

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
Jimbo
  • 22,379
  • 42
  • 117
  • 159
  • Please check the following link here - [https://stackoverflow.com/questions/20419515/window-getselection-of-textarea-not-working-in-firefox/20427804#20427804?newreg=c150bc84d4ae4031888cc57edc0eca3d](https://stackoverflow.com/questions/20419515/window-getselection-of-textarea-not-working-in-firefox/20427804#20427804?newreg=c150bc84d4ae4031888cc57edc0eca3d) – codebreadbutter Aug 18 '17 at 00:06

6 Answers6

65

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:

function isTextSelected(input) {
    if (typeof input.selectionStart == "number") {
        return input.selectionStart == 0 && input.selectionEnd == input.value.length;
    } else if (typeof document.selection != "undefined") {
        input.focus();
        return document.selection.createRange().text == input.value;
    }
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 30
    So, how do they look guys? – darkAsPitch Feb 09 '12 at 16:29
  • FYI, this will return true if the input is empty. – Jack May 22 '14 at 19:28
  • @Jack: True, although I'm pretty sure it's deliberate. It's not intuitively clear to me what the behaviour should be when the input is empty. – Tim Down May 22 '14 at 21:19
  • Most recently, to get the selected text - document.getSelection().toString() – Sunny R Gupta Jan 16 '17 at 06:37
  • 1
    @SunnyRGupta: That doesn't work on Firefox. The cross-browser and standardized way of getting the selection from an input or textarea is still `selectionStart` and `selectionEnd`. The second branch is for IE <= 8 and can be safely omitted now unless you need to support IE 8 but isn't doing any harm. – Tim Down Jan 16 '17 at 11:19
  • I learnt about the API via MDN - https://developer.mozilla.org/en-US/docs/Web/API/Selection/toString – Sunny R Gupta Jan 17 '17 at 09:30
  • @SunnyRGupta: Yes, that's the correct API for dealing with selections within a document, except for inputs and textareas, which have a different API. – Tim Down Jan 18 '17 at 10:42
  • But then since we are listening to onChange/Blue on a textbox, the selection, if any would be within the input/textarea itself. – Sunny R Gupta Jan 18 '17 at 10:46
  • @SunnyRGupta: Right. I don't understand what you're getting at though. The rule is simply this: if the selection is in an input or textarea, use `selectionStart` and `selectionEnd` properties of the input/textarea. Otherwise, use `window.getSelection()`/`document.getSelection()`. – Tim Down Jan 18 '17 at 16:55
  • No worries, I was just trying to say there is no need to handle cases since the single `document.getSelection` would effectively solve the problem for OP here. :) – Sunny R Gupta Jan 19 '17 at 05:51
  • 1
    @SunnyRGupta: No, it wouldn't, because `document.getSelection()` doesn't work for selections in inputs and textareas in Firefox. – Tim Down Jan 19 '17 at 10:35
  • @Mayank: Yep. The first branch is standards-based and works in all major browsers released since 2011. The second branch is for Internet Explorer versions 4-8. – Tim Down Jan 04 '19 at 15:21
15

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 the input's value.

In modern browsers I achieved it by doing:

document.getSelection().toString() === input.value // edited

Hope this helps someone.

Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
  • 1
    A more correct example would be: var selected = document.getSelection().toString() === document.getElementById('inputName').value; Unfortunately it does not work in all browsers. – RWC Apr 19 '17 at 07:24
  • But the code above works in all modern browsers, no? – Sunny R Gupta Apr 19 '17 at 07:38
4

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/

function getSelection(textbox) 
{
   var selectedText = null;
   var activeElement = document.activeElement;

   // all browsers (including IE9 and up), except IE before version 9 
   if(window.getSelection && activeElement && 
      (activeElement.tagName.toLowerCase() == "textarea" || (activeElement.tagName.toLowerCase() == "input" && activeElement.type.toLowerCase() == "text")) &&
      activeElement === textbox) 
   {
      var startIndex = textbox.selectionStart;
      var endIndex = textbox.selectionEnd;

      if(endIndex - startIndex > 0)
      {
          var text = textbox.value;
          selectedText = text.substring(textbox.selectionStart, textbox.selectionEnd);
      }
   }
   else if (document.selection && document.selection.type == "Text" &&  document.selection.createRange) // All Internet Explorer
   {       
       var range = document.selection.createRange();
       selectedText = range.text;
   }    

    return selectedText;
}
Mr_CSharp
  • 69
  • 1
  • This type of approach worked better than the accepted answer for my use case, thanks to the addition of checking whether the given input field is also the active element. – Lorien Brune May 04 '22 at 21:06
2

Instead of hitting the wall of digits dots and selections you can climb it easily by checking the value in onchange event.

HTML:

<input type="text" onchange="ValidateNumericValue(this);" />

JS:

function ValidateNumericValue(oInput) {
    var blnRequired = true; //set to false if allowing empty value

    var sValue = oInput.value;
    if (blnRequired && sValue.length == 0) {
        alert("Please enter a value");
        oInput.focus();
        return;
    }

    var numericValue = parseFloat(sValue);
    if (isNaN(numericValue)) {
        alert("Value is not a valid number");
        oInput.focus();
        return;
    }

    //put back to make 2.15A back to 2.15
    oInput.value = numericValue + "";
}

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/

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
2

If you're use case is simply to know whether any text is selected.

The difference between selectionStart and selectionEnd is always zero when no text is selected irrespective of cursor position.

So this should do the trick

const element = document.getElementById('inputbox');

const isTextSelected = element.selectionStart - element.selectionEnd;
bkmalan
  • 174
  • 1
  • 3
1

You can get the id of the selected element in the page with the following code:

elem_offset = document.getSelection().anchorOffset;
elem = document.getSelection().anchorNode.childNodes[elem_offset];
alert(elem.id);
Raposo
  • 499
  • 5
  • 4