Get selected text in an input box

送分小仙女□ 提交于 2019-12-23 15:00:27

问题


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.


回答1:


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" />



回答2:


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)



来源:https://stackoverflow.com/questions/32809168/get-selected-text-in-an-input-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!