简体   繁体   中英

Get selected text in an input box

Is it possible to get the selected text in an input box of a website, using either jQuery or vanilla JavaScript?

I have tried with var selectedText = window.getSelection().toString(); , but this code only gets the text in a paragraph and not in an input box .


EDIT: Maybe I was unclear, I want to get the text from a website that I didn't create. I'm building a Chrome extension and I need to get the text from an input box of a website.

Came with solution Find below

 function disp() { var text = document.getElementById("text"); var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart); alert(t); } 
 <TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR> <INPUT type="button" onclick="disp()" value="show selected" /> 

If you don't mind using jQuery plugins you can accomplish that by using this one http://madapaja.github.io/jquery.selection/

It's flexible (You can use it both for inputs and for paragraphs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM