John Doe
John Doe

Reputation: 91

Select specific li element which start's with selected character

I hope someone can help to solve my problem.

I have list of cities like this:

<ul class="cities">
   <li>New York</li>
   <li>New York 2</li>
   <li>Chicago</li>
   <li>Chicago 2</li>
   <li>Etc.</li>
</ul>

I want to select appropriate city which starts with pressed character on keyboard. For example if I press 'N' it will select 'New York', if I press once again, then it will select 'New York 2' and so on.

So far I have jQuery code:

jQuery(document).keypress(function(event){
    // Deselect all others
    $(".cities li").each(function() {
        if($(this).hasClass('active')) {
            $(this).removeClass('active');
        }
    });

    $(".cities li").each(function() {
        var li_text = $(this).text();

        // check if pressed character match first li element character and select it by adding 'active' class
        if(li_text.charAt(0).toLowerCase() == String.fromCharCode(event.which).toLowerCase())
        {
            $(this).addClass('active');

        }
    });
});

The struggle is that it is selecting all elements with pressed character. :(

P.S. By selecting I mean adding 'active' class to li element.

Upvotes: 1

Views: 226

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this more effectively you can use a regular expression inside filter() which returns only the elements whose first character matches the pressed key. Try this:

$(document).on('keypress', function(e) {
  var letter = String.fromCharCode(e.which).toLowerCase();
  var re = new RegExp('^' + letter, 'i');

  $li = $('.cities li').removeClass('active').filter(function() {
    return re.test($(this).text().trim());
  }).addClass('active');
});
.active { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="cities">
  <li>New York</li>
  <li>New York 2</li>
  <li>Chicago</li>
  <li>Chicago 2</li>
  <li>Etc.</li>
</ul>

Upvotes: 1

Related Questions