I have a standard input field:
<input type='text' id='txt'>
And let's say the contents are foo bar
.
Now, I want to be able to dynamically, with javascript/jQuery highlight the word 'bar' in that input field. I've tried using things such as $('#txt').setSelectionStart(5);
or $('#txt').selectionStart(5);
, but nothing seems to work. How can I do this? All the examples point to code within the $('#txt').select()
scope, but I need to be able to change it from other places.
Edit By highlight I mean select or highlight a word in the same way you would select a word with your mouse to edit it or copy. I do not mean to simply color the word differently.
Second Edit After an entire morning, I finally managed it. My big hangup was not preventing default when pressing an arrow key. here is the jsfiddle: http://jsfiddle.net/31mts93v/3/