简体   繁体   中英

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

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM