3

I want my script to select just a part of the text inside a text field (<input type="text"). How can I do this?

2
  • To clarify, you want a way to set the current selection by specifying a start and end index? Or by matching a regex? Or by modifying the existing selection in some predetermined fashion? Or what? Commented Jun 8, 2010 at 16:16
  • 1
    Possible duplicate of stackoverflow.com/questions/646611/… Commented Jun 8, 2010 at 16:41

2 Answers 2

2

You will need to use Range, and cross-browser compatibility will probably be an issue.

Quirksmode: Creating a Range object from a Selection object

If jQuery is an option, here is a function you can use (reference)...

$.fn.selectRange = function(start, end) { return this.each(function() { if(this.setSelectionRange) { this.focus(); this.setSelectionRange(start, end); } else if(this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } }); }; 
Sign up to request clarification or add additional context in comments.

1 Comment

Why do you need jQuery for that?
0

Check out Programmatically selecting partial text in an input field (may be a duplicate...)

Also, a helpful implementation concerning selected text and cursor position can be found here: http://javascript.nwbox.com/cursor_position/

1 Comment

Yup, it seems that my question is a duplicate. It's weird that I never seem to find an existing Stack Overflow question that solves my problem until I post the duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.