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?
Thanks!
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?
Thanks!
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.
.
<input type="text" id="test" name="test" value="split me up" />
.
var words = $('#test').val().split(' ');
words[0] == 'split' // true
For text <input> elements, the following will do the job. The example selects just the word "two" in the input:
<input id="i" type="text" value="One two three">
<script type="text/javascript">
function setInputSelection(input, startPos, endPos) {
if (typeof input.selectionStart != "undefined") {
input.selectionStart = startPos;
input.selectionEnd = endPos;
} else if (document.selection && document.selection.createRange) {
// IE branch
input.focus();
input.select();
var range = document.selection.createRange();
range.collapse(true);
range.moveEnd("character", endPos);
range.moveStart("character", startPos);
range.select();
}
}
window.onload = function() {
setInputSelection(document.getElementById("i"), 4, 7);
};
</script>