Select part of the text in a textbox with javascript

There was a brief discussion on the Tracks mailing list over the way its autocomplete works (the project uses Scriptaculous’s nice Autocomplete widget in local mode): should it automatically fill in the entire word once enough text is entered to match one of the choices (annoying if you have to backspace because the guess was wrong) or make you hit tab or enter to fill in the suggestion. To make a long story short, I suggested a third approach – fill in the remainder of the match selected, so if its wrong, the user can type over it, like this:


This isn’t rocket science and has been done forever, but I didn’t find a single good reference on how to select just part of the text in a text box. Scriptaculous and prototype don’t support it at the present time, and like anything good in browser-land, there’s at least two different ways to skin this cat. The IE way, and everyone else’s way (actually I don’t know which way safari and opera work, but the code here does work for them too).

I saw one of the YUI widgets supported “typeahead” so I looked through its code to find the relevent javascript calls – for IE its “createTextRange” and for firefox its “setSelectionRange”. Combine those and you get the following, which I’ve tested as working on IE 6 (or was it 7?), Firefox (mac), opera (mac) and safari.

function selectSomeText(element,begin,end)
if (element.setSelectionRange)
else if (element.createTextRange)
var range = element.createTextRange();

One of these days I’ll refactor the code I wrote to test this with scriptactulous and throw that up here as well.

One thought on “Select part of the text in a textbox with javascript”

  1. Is element the value of the input-field? Where do you get begin and end from? I try do write a function like that but still have very tiny feeling vor JS :'(

Leave a Reply

Your email address will not be published. Required fields are marked *