Sebastian Nordqvist
Sebastian Nordqvist

Reputation: 68

Select the first field from jQuery autocomplete function automatically

When I mouseover a field in my autocomplete list it adds a class named selected. I want it to do that by default on the first line as soon as you start typing. How would i select the first element in that list and change it's class?

I'm using this now but it flickers a lot.

$('.name').eq(0).addClass('selected');

Upvotes: 0

Views: 415

Answers (2)

Jens Roland
Jens Roland

Reputation: 27770

I'm betting the flicker is caused by calling it on every keyup event. You need to 'debounce' the function call.

Debouncing functions with jQuery:

http://benalman.com/projects/jquery-throttle-debounce-plugin/

Like this:

$('input:text').keyup( $.debounce( 250, function() {
  // run autocomplete routine / ajax call here
  $('.name').eq(0).addClass('selected');
}) );

That requires a jQuery plugin of course, so if you'd rather have a minimal-footprint version, use John Hann's pure-Javascript version:

Debouncing functions with pure Javascript and less code:

Or if you don't want to use another plugin, debouncing is as easy as:

var debounce = function (func, threshold, execAsap) {

  var timeout;

  return function debounced () {
    var obj = this, args = arguments;
    function delayed () {
        if (!execAsap)
            func.apply(obj, args);
        timeout = null; 
    };

    if (timeout)
        clearTimeout(timeout);
    else if (execAsap)
        func.apply(obj, args);

    timeout = setTimeout(delayed, threshold || 100); 
  };
};

Usage:

$('input:text').keyup( debounce(function() {
  // run autocomplete routine / ajax call here
  $('.name').eq(0).addClass('selected');
}), 250, false );

Upvotes: 0

k4t434sis
k4t434sis

Reputation: 519

You may want to use jQuery's toggleClass() and first() for that.

$('.name').first().toggleClass('selected');

Upvotes: 1

Related Questions