如何使用 JavaScript 从文本框控件中获取选定的文本

发布于 2024-07-08 06:42:04 字数 332 浏览 13 评论 0原文

我有一个文本框和一个链接按钮。 当我编写一些文本,选择其中一些文本,然后单击链接按钮时,从文本框中选择的文本必须显示在消息框中。

我该怎么做?


当我单击下面文本框的提交按钮时,消息框必须显示 Lorem ipsum。 因为在区域中选择了“Lorem ipsum”。


如果我从页面中选择任何文本并单击提交按钮,它就可以工作,但是如果我将文本写入文本框并创建它,它就不能工作。 因为当我点击另一个空间时,文本框的选择被取消。

现在的问题是,当我从文本框中选择文本并单击任何其他控件或空间时,所选的文本仍然必须被选择。

该怎么做呢?

I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.

How can I do it?


When I click the submit button for the textbox below, the message box must show Lorem ipsum. Because "Lorem ipsum" is selected in the area.


If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.

Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.

How is it to be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

下壹個目標 2024-07-15 06:42:04

好的,这是我的代码:

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;

  if (textComponent.selectionStart !== undefined)
  { // Standards-compliant version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  }
  else if (document.selection !== undefined)
  { // Internet Explorer version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

  alert("You selected: " + selectedText);
}

问题是,虽然我为 Internet Explorer 提供的代码在很多网站上都给出了,但我无法使其在我的 Internet Explorer 6 在我当前的系统上。 也许它对你有用,这就是我给出它的原因。

您寻找的技巧可能是 .focus() 调用将焦点返回到文本区域,以便重新激活选择。

我通过 onKeyDown 事件得到了正确的结果(选择内容):

document.onkeydown = function (e) { ShowSelection(); }

所以代码是正确的。 同样,问题是通过单击按钮进行选择......我继续搜索。

我对使用 li 标记绘制的按钮没有任何成功,因为当我们单击它时,Internet Explorer 会取消选择之前的选择。 上面的代码使用一个简单的 input 按钮,但是......

OK, here is the code I have:

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;

  if (textComponent.selectionStart !== undefined)
  { // Standards-compliant version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  }
  else if (document.selection !== undefined)
  { // Internet Explorer version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

  alert("You selected: " + selectedText);
}

The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of Internet Explorer 6 on my current system. Perhaps it will work for you, and that's why I give it.

The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.

I got the right result (the selection content) with the onKeyDown event:

document.onkeydown = function (e) { ShowSelection(); }

So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.

I didn't have any success with a button drawn with a li tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple input button, though...

救星 2024-07-15 06:42:04

这是一个更简单的解决方案,基于文本选择发生在 mouseup 上的事实,因此我们为此添加一个事件侦听器:

document.querySelector('textarea').addEventListener('mouseup', function () {
  window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
  // window.getSelection().toString();
});
<textarea>
  Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>

这适用于所有浏览器。

如果您还想通过键盘处理选择,请使用相同的代码为 keyup 添加另一个事件侦听器。

如果不是这个 2001 年提交的 Firefox 错误< /a>(是的,14 年前),我们可以用 window.getSelection().toString() 替换分配给 window.mySelection 的值,该值适用于 IE9+和所有现代浏览器,并且还可以获取在 DOM 的非文本区域部分中进行的选择。

Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:

document.querySelector('textarea').addEventListener('mouseup', function () {
  window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
  // window.getSelection().toString();
});
<textarea>
  Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>

This works in all browsers.

If you also want to handle selection via the keyboard, add another event listener for keyup, with the same code.

If it weren't for this Firefox bug filed back in 2001 (yes, 14 years ago), we could replace the value assigned to window.mySelection with window.getSelection().toString(), which works in IE9+ and all modern browsers, and also gets the selection made in non-textarea parts of the DOM.

您的好友蓝忘机已上羡 2024-07-15 06:42:04
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="Select text and click here" />

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="Select text and click here" />

雪落纷纷 2024-07-15 06:42:04

对于 Opera、Firefox 和 Safari,您可以使用以下函数:

function getTextFieldSelection(textField) {
    return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}

然后,您只需将对文本字段元素(如 textarea 或 input 元素)的引用传递给该函数:

alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));

或者,如果您想要

HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
    var ss = this.selectionStart;
    var se = this.selectionEnd;
    if (typeof ss === "number" && typeof se === "number") {
        return this.value.substring(this.selectionStart, this.selectionEnd);
    }
    return "";
};

然后,您只需执行以下操作:

alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());

例如。

For Opera, Firefox and Safari, you can use the following function:

function getTextFieldSelection(textField) {
    return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}

Then, you just pass a reference to a text field element (like a textarea or input element) to the function:

alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));

Or, if you want <textarea> and <input> to have a getSelection() function of their own:

HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
    var ss = this.selectionStart;
    var se = this.selectionEnd;
    if (typeof ss === "number" && typeof se === "number") {
        return this.value.substring(this.selectionStart, this.selectionEnd);
    }
    return "";
};

Then, you'd just do:

alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());

for example.

往日 2024-07-15 06:42:04

我是 jQuery-textrange忠实粉丝

下面是一个非常小的、独立的示例。 下载jquery-textrange.js并将其复制到同一文件夹。

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>jquery-textrange</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="jquery-textrange.js"></script>

    <script>
        /* Run on document load */
        $(document).ready(function() {
            /* Run on any change of 'textarea' **/
            $('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {

                /* The magic is on this line **/
                var range = $(this).textrange();

                /* Stuff into selectedId. I wanted to
                   store this is a input field so it
                   can be submitted in a form. */
                $('#selectedId').val(range.text);
            });
        });
    </script>
</head>

<body>
    The smallest example possible using
    <a href="https://github.com/dwieeb/jquery-textrange">
       jquery-textrange
    </a><br/>
    <textarea id="textareaId">Some random content.</textarea><br/>
    <input type="text" id="selectedId"></input>

</body>

</html>

I am a big fan of jQuery-textrange.

Below is a very small, self-contained, example. Download jquery-textrange.js and copy it to the same folder.

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>jquery-textrange</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="jquery-textrange.js"></script>

    <script>
        /* Run on document load */
        $(document).ready(function() {
            /* Run on any change of 'textarea' **/
            $('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {

                /* The magic is on this line **/
                var range = $(this).textrange();

                /* Stuff into selectedId. I wanted to
                   store this is a input field so it
                   can be submitted in a form. */
                $('#selectedId').val(range.text);
            });
        });
    </script>
</head>

<body>
    The smallest example possible using
    <a href="https://github.com/dwieeb/jquery-textrange">
       jquery-textrange
    </a><br/>
    <textarea id="textareaId">Some random content.</textarea><br/>
    <input type="text" id="selectedId"></input>

</body>

</html>
南风几经秋 2024-07-15 06:42:04
// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);

// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);
// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);

// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文