nani0077
nani0077

Reputation: 119

Jquery Fill search box with selected text using arrow key Issue

Requirement: When the arrow down is pressed, the first li with the matched terms should be highlighted and it's content should be placed in the search box ? And so on if I press the down arrow again ..

Here is the DEMO

Problem: In the above demo when I press down arrow it selecting all last li text

I used this Jquery

var $expandBtns = $('.expandBtn');
var $span;

//Search    
$('input#catInput').keyup(function(e) {
  var searchTerms = $(this).val();
  console.log('Input change');
  if (searchTerms == '') {
    $expandBtns.each(function() {
      var $subList = $(this).siblings('ul');
      $subList.hide('slow');
    });
  }
  $('#orgCat li').each(function() {
    var $li = $(this);
    var hasMatch = searchTerms.length == 0 || $li.text().toLowerCase().indexOf(searchTerms.toLowerCase()) > 0;
    $li.toggle(hasMatch).removeClass('searchActiveLi');
    if ($li.is(':hidden')) {
      $li.closest('ul').show('slow');
    }

    if(e.keyCode == 40 && searchTerms.length !=0){ //highlighting selected li using down arrow key
    if($li.children('ul').length <= 0)
        $li.addClass('searchActiveLi');
      $('#catInput').val($('.searchActiveLi').text());
    }    
  });

  /*if(e.keyCode == 40 && searchTerms.length != 0){
  //alert(searchTerms);
  var m = $('.expandBtn:contains("'+searchTerms+'")').text();
  alert(m);
  $that = $('#orgCat li');
  $('#orgCat .searchActiveLi').removeClass('searchActiveLi');
  $that.addClass('searchActiveLi');
  }
  */
});

from last two days I am trying but no use, please help me

Upvotes: 1

Views: 123

Answers (1)

This might be what you want to achieve

Demo

if (e.keyCode == 40 && searchTerms.length != 0) { //highlighting selected li using down arrow key
  if ($li.children('ul').length <= 0)
    if ($li.text().toLowerCase().indexOf(searchTerms.toLowerCase()) > -1) {
      $li.addClass('searchActiveLi');
    }
  $('#catInput').val($('.searchActiveLi').text().trim());
}

This will check if the li contains the search word, if so then add a class to the li.

Upvotes: 1

Related Questions