I want my script to select just a part of the text inside a text field (<input type="text"). How can I do this?
- 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?warrenm– warrenm2010-06-08 16:16:31 +00:00Commented Jun 8, 2010 at 16:16
- 1Possible duplicate of stackoverflow.com/questions/646611/…marapet– marapet2010-06-08 16:41:32 +00:00Commented Jun 8, 2010 at 16:41
Add a comment |
2 Answers
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(); } }); }; 1 Comment
Tim Down
Why do you need jQuery for that?
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
Pieter
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.