jessy
jessy

Reputation: 19

How do I use a for loop in jquery?

jQuery(function($) {
   
   for (var i = 0; i < 81; i++) {
    
      var input = $('#cell-'+i);
      console.log(input);
      input.on('keydown', function() {
        var key = event.keyCode || event.charCode;

        if( key == 8 || key == 46 )
            input.removeClass("text-danger");

      });
   }
    
   
});
.text-danger { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="cell-0" type="text" maxlength="1" class="text-danger">
<input id="cell-1" type="text" maxlength="1" class="text-danger">

I have several input text fields in a form. When the user hits 'backspace' or 'del' i want to remove the class. This is not working with the for loop, however it works if i don't use the loop (but i don't want to repeat myself) like this:

    jQuery(function($) {
   
      $('#cell-0').on('keydown', function() {
        var key = event.keyCode || event.charCode;

        if( key == 8 || key == 46 )
            $('#cell-0').removeClass("text-danger");

      });

      $('#cell-1').on('keydown', function() {
        var key = event.keyCode || event.charCode;

        if( key == 8 || key == 46 )
            $('#cell-1').removeClass("text-danger");

      });
   
  });

What am I doing wrong?

Upvotes: 0

Views: 210

Answers (1)

Tomalak
Tomalak

Reputation: 338406

How do i use for loop in jquery?

It's best when you don't.

What you really want is a delegated event handler at the document level.

$(document).on('keydown', 'input[id^="cell-"]', function(e) {
  var key = e.keyCode;

  console.log(key, e.key);

  if (key == 8 || key == 46) {
    $(this).removeClass("text-danger");
  }
});
.text-danger {
  border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="cell-0" type="text" maxlength="1" class="text-danger">
<input id="cell-1" type="text" maxlength="1" class="text-danger">

This will react to all keydown events that occur at <input> elements having an ID that starts with cell-. You might want to introduce a common class for these elements, that's better than relying on part of their ID.

Upvotes: 2

Related Questions