Search code examples
javascriptjqueryhtmldjangokeyup

jQuery keyup event is activated multiple times, doubling every time it's triggered


I added an auto-completing search bar to my website. It queries the database for elements that start with the entered string every time the user types a new character.

It works fine, however every time the user adds another character or does any keyboard event like backspace it doubles the event activation. 1,2,4,8,16, etc.. times.

How could I make it so that it doesn't accumulate event triggers and only triggers .keyup() one time per keyboard event?

Here's the HTML code:

<form>
<div class="nav-item">
    <input class="search-query form-control" placeholder="Items" 
       type="text"  name="items" value="" id="id1" />
</div>
</form>
<hr>
<div id="id2">
</div>

And here's the jQuery code:

$(document).ready(function() {
  $('#id1').keyup(function(){
    var query = $(this).val();
    $.get('/url/', {items: query}, function(data){
      $('#id2').html(data);
    });
  });
});

Solution

  • I finally figured out how to fix it.

    For anyone interested, here's how I did it:

    (Obviously more experienced user please feel free to correct me if I am wrong!)

    Basically, adding a .one() method solved it. As it detaches the event from the "#id1" element by only executing it once.

    Here's the functional code:

    $(document).ready(function() {
      $('#id1').one("keyup", function(){
        var query = $(this).val();
        $.get('/url/', {items: query}, function(data){
          $('#id2').html(data);
        });
      });
    });
    


    For comparison here's the old one as posted above again:

    $(document).ready(function() {
      $('#id1').keyup(function(){
        var query = $(this).val();
        $.get('/url/', {items: query}, function(data){
          $('#id2').html(data);
        });
      });
    });