Javascript 如何知道文本框中的文本是否被选中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5001608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:11:29  来源:igfitidea点击:

How to know if the text in a textbox is selected?

javascriptjqueryinputtextbox

提问by Jimbo

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.

我有<input type='text'>只允许数字字符的文本框,并且不会让用户多次输入点 (.)。问题是,如果文本框中的文本被选中,用户打算用点覆盖内容,因此允许!问题是,如何在 javascript 中判断该文本框中的文本是否被选中。

Thanks

谢谢

回答by Tim Down

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/

示例: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;
    }
}

回答by Sunny R Gupta

2017 Specific Answer- Faced the same issue recently.

2017 年具体答案- 最近面临同样的问题。

We were allowing users to enter only 3 digits at a time. When the user tried to enter the fourth character we returned false.

我们只允许用户一次输入 3 位数字。当用户尝试输入第四个字符时,我们返回 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 valuewas same as the input's value.

从蒂姆的回答中得到提示。我明白我想看看它是否selection valueinput's value.

In modern browsers I achieved it by doing:

在现代浏览器中,我通过以下方式实现了它:

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

Hope this helps someone.

希望这可以帮助某人。

回答by Mr_CSharp

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/

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;
}

回答by Shadow Wizard is Ear For You

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

您可以通过检查onchange事件中的值轻松攀爬数字点和选择的墙壁,而不是碰到数字点和选择的墙壁。

HTML:

HTML:

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

JS:

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/

现场测试用例:http: //jsfiddle.net/yahavbr/NFhay/

回答by Raposo

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

您可以使用以下代码获取页面中所选元素的 id:

elem_offset = document.getSelection().anchorOffset;
elem = document.getSelection().anchorNode.childNodes[elem_offset];
alert(elem.id);