使用jQuery选择输入框内部的字符串

时间:2022-01-22 06:47:33

I am trying to figure out how to highlight just some part of text inside an input box using jQuery. It's quite simple to highlight the entire contents of the input box but how do you highlight just one word or couple of letters?

我试图弄清楚如何使用jQuery突出显示输入框内的文本的某些部分。突出显示输入框的全部内容非常简单,但是如何突出显示一个单词或几个字母呢?

Thanks!

谢谢!

2 个解决方案

#1


32  

For text <input> elements, the following will do the job. The example selects just the word "two" in the input:

对于text 元素,以下内容将完成此任务。该示例仅在输入中选择单词“two”:

function setInputSelection(input, startPos, endPos) {
    input.focus();
    if (typeof input.selectionStart != "undefined") {
        input.selectionStart = startPos;
        input.selectionEnd = endPos;
    } else if (document.selection && document.selection.createRange) {
        // IE branch
        input.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
    }
}

document.getElementById("setSelection").onmousedown = function() {
    var input = document.getElementById("i");
    setInputSelection(input, 4, 7);
    return false;
};
<input id="i" type="text" value="One two three">
<input type="button" value="Set selection" id="setSelection">

#2


-3  

You will need to select the entire value, and then manipulate the string in code. Depending on what you're trying to do with the words, you might look in to using regular expressions to match certain words/letters.

您需要选择整个值,然后在代码中操作字符串。根据您尝试对单词执行的操作,您可能会使用正则表达式来匹配某些单词/字母。

#1


32  

For text <input> elements, the following will do the job. The example selects just the word "two" in the input:

对于text 元素,以下内容将完成此任务。该示例仅在输入中选择单词“two”:

function setInputSelection(input, startPos, endPos) {
    input.focus();
    if (typeof input.selectionStart != "undefined") {
        input.selectionStart = startPos;
        input.selectionEnd = endPos;
    } else if (document.selection && document.selection.createRange) {
        // IE branch
        input.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
    }
}

document.getElementById("setSelection").onmousedown = function() {
    var input = document.getElementById("i");
    setInputSelection(input, 4, 7);
    return false;
};
<input id="i" type="text" value="One two three">
<input type="button" value="Set selection" id="setSelection">

#2


-3  

You will need to select the entire value, and then manipulate the string in code. Depending on what you're trying to do with the words, you might look in to using regular expressions to match certain words/letters.

您需要选择整个值,然后在代码中操作字符串。根据您尝试对单词执行的操作,您可能会使用正则表达式来匹配某些单词/字母。