Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    May 2009
    Thanked 0 Times in 0 Posts

    select/highlight a piece of a HTML textbox using Javascript


    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.


  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Thanked 4,747 Times in 4,709 Posts
    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.

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Thanked 603 Times in 583 Posts
    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...
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts