jQuery Rails regain focus on live search input box

928 views Asked by At

I'm pretty new to jQuery and was following a tutorial on how to make a live search bar. The live search bar works great, except that after every character entered, the ajax request to get the results occurs and I lose focus on my text box. This requires me to click on the search box over and over for each character... I'm wondering, how can I get the cursor back at the end of the string?

$(function() {
  $('#search_user input').live('keyup', function(event) {
    $.get($('#search_user').attr('action'), $('#search_user').serialize(), null, "script");
    return false;
  });
});
1

There are 1 answers

1
Marcus Whybrow On

You could try adding $(this).focus(); to the end of your callback function if for whatever reason focus is being lost. For example:

$(function() {
    $('#search_user input').live('keyup', function(event) {
        var $su = $('#search_user');
        $.get($su.attr('action'), $su.serialize(), null, "script");
        $(this).focus();
        return false;
    });
});