JS onclick select partial text in input - start from cursor position to the end of string (afterCaret)

1.8k views Asked by At

I need tricky function, when I OnClick on the input field it will select text from cursor position (afterCaret) to the end of text value.

<input> I am input example textfield text </input>

When I will put cursor by clicking by mouse.. let's say in the middle of word "exa | mple", output should be highlighted text: "mple textfield text"

(after that I will press Delete :) but I dont wanna delete it automatically by function, only select)

I found this, perfect example, but I'm not able to use it right with my knowledge :( http://javascript.nwbox.com/cursor_position/

1

There are 1 answers

3
John S On BEST ANSWER

HTML:

<input id="text" type="text" value="EXAMPLE" size="20" />

JavaScript Version:

document.getElementById('text').addEventListener('click', function() {
    var length = this.value.length;
    this.setSelectionRange(this.selectionStart, length);
},
false);

jsfiddle

JQuery Version:

$('#text').on('click', function() {
    var length = $(this).val().length;
    this.setSelectionRange(this.selectionStart, length);
}); 

jsfiddle