0

I am using jQuery on method to do a search and populate my div with the search results. I have an input text box which is part of the div's contents. I am using the keyup event to read the text entered and then using ajax to call my server and do the search. When I return the results I populate the text box with the text that has been typed so far. The rest of the content I return is the search results. This is all working fine.

What I want to however is have the focus be placed in my input text box and the cursor placed after the last character typed so that the user can just keep typing and the search results will keep changing with every keystroke. I imagine there is some way to do this with jQuery and JavaScript but I don't know how.

Edit: Maybe I wasn't clear, but I found the answer at this question: jQuery - Place cursor in input field when link clicked.

Basically all I needed to do was:

var searchBox = $("#search");

searchBox.focus();

searchBox[0].selectionStart = searchBox[0].selectionEnd = searchBox.val().length;

Community
  • 1
  • 1
Seth F
  • 23
  • 1
  • 5

2 Answers2

0

I think you can use select2 plugin. Take a look here, maybe it can help you: http://ivaynberg.github.io/select2/

0

If I understand correctly, you need to do less rather than more.

You say, "when I return the results I populate the text box with the text that has been typed so far".

Why? The text that has been typed so far is already in the text box, so it should not need to be replaced. By not replacing the text, the user will be able to carry on typing.

There's an additional aspect that you may not have considered ...

The user will almost undoubtedly be able to out-type the ajax responses, so you should take measures to abort an unfulfilled ajax request before issuing a new one. This is made simple by the jQuery jqXHR object returned by $.ajax() (and its shorthand versions) in the form of an abort() method.

Failure to abort could result in the wrong set of search results being displayed against the current text, as the ajax responses are not guaranteed to arrive back in the same order their requests were issued.

Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44