View Full Version : select/highlight a piece of a HTML textbox using Javascript

05-11-2009, 02:14 PM

I am developing a web-application using ASP.NET 3.5,javascript and ajax

I have a form with two textboxes with ID's firstname and lastname. Both of them have the attribute runat="server".

When the user types, I use AJAX to request the possible names. For example if the user types an 'a' in the textbox with ID firstname

the textbox will trigger a javascript function that uses AJAX to get the first person in the database wich firstname starts with an 'a'.

The callback function recieves this firstname and fills it in in the textbox. When i do this the content of the textbox will be the requested name

and the cursor is at the end of the textbox. This prevents the user of continuing typing the rest of the name.

Is it possible to select a part of the text in a textbox? This way the user can keep typing while the textbox suggests other names.


Old Pedant
05-11-2009, 10:28 PM
I don't know any cross-browser way to do exactly what you ask, but how about something like this:

var prior = "";
function fun( fld )
prior = fld.value;
fld.value = prior + "123456"; // simulate AJAX adding on its text
<input name="foo" onkeydown="this.value=prior;return true;" onkeyup="fun(this);">

Basically, any time the user hits a key, it "forgets" about what the AJAX added to the field and then the onkeyup invokes AJAX again and may or may not thus alter what the user has typed.

rnd me
05-11-2009, 10:41 PM
input.selectionStart and input.selectionEnd.

selected text typically gets replaced by the next keystroke, so start selecting at oldvalue.length and end at value.length...