1

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/

yan
  • 15
  • 3

1 Answers1

0

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

John S
  • 21,212
  • 8
  • 46
  • 56
  • wow :) you rock! hope it helps also to others, coz I didn't find answer to this in here :) – yan Aug 16 '14 at 03:21
  • might be better to be doing this call on "focus" no? – pim Aug 08 '15 at 15:59
  • 1
    @PimBrouwers - Your suggestion appears to have no effect. When you click on the input, both events are fired, but the `click` event fires after the `focus` event. When you tab to an input, only `focus` is fired, but the normal behavior is that the entire text is selected. [jsfiddle](http://jsfiddle.net/qfg2fovb/1/) – John S Aug 08 '15 at 16:46