-1

Can I check if a value in a text input is selected or not using javascript?

This image shows an unselected text input: http://image.ohozaa.com/i/ee0/Sn5ZWI.jpg

And this shows one that has selected text: http://image.ohozaa.com/i/1dd/mOdGCt.jpg

How can I use javascript to check this?

  • possible duplicate of [Javascript get selected text from any textinput/textarea on the page](http://stackoverflow.com/questions/6416020/javascript-get-selected-text-from-any-textinput-textarea-on-the-page) – George Dec 03 '14 at 16:53

2 Answers2

0

You can use this:

function getSelectionText() {
var text = "";
if (window.getSelection) {
    text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
}
return text;
}

It works fine on both text inputs and regular text on the page. This is actually a duplicate of Get the Highlighted/Selected text

Community
  • 1
  • 1
Matthew
  • 4,149
  • 2
  • 26
  • 53
0

Try it bro

 //javascript
function getText(elem) {
if(elem.tagName === "TEXTAREA" ||
   (elem.tagName === "INPUT" && elem.type === "text")) {
    return elem.value.substring(elem.selectionStart,
                                elem.selectionEnd);
}
return null;
}

setInterval(function() {
var txt = getText(document.activeElement);
document.getElementById('div').innerHTML =
    txt === null ? 'no input selected' : txt;
}, 100);


  //html
<input type="text"></input>
<div id="div"></div>

demo fiddle http://jsfiddle.net/rBPte/1/
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103