Skip to content

Autonumbering upon keyboard press

I have an autonumbering when Ctrl and Enter are pressed. My current problem is, when i start my autonumbering at the 3rd textbox, my 2nd textbox is getting affected. How can i retain the other values of my textbox? The textbox before them should not change their value.

Thank you.

$(document).on('keyup', '.leg', function(e) {
  let value = parseInt(e.target.value);
  if ((e.ctrlKey || e.metaKey) && (e.keyCode == 17 || e.keyCode == 13)) {
    //loop through all values...
    $(".leg").each(function(i) {
      if (i !== 0) {
        $(this).val(++value); //assign new value..
        $(this).trigger("change") //call your change event to handle further...
      }
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="leg">
<input type="text" class="leg">
<input type="text" class="leg">
<input type="text" class="leg">

Answer

You can create a variable to keep track of whether or not the each loop has crossed the target element and then only modify the input’s value when it is true. This will make sure you only modify the inputs after the target.

See runChange in example:

$(document).on('keyup', '.leg', function(e) {
  let value = parseInt(e.target.value);
  if ((e.ctrlKey || e.metaKey) && (e.keyCode == 17 || e.keyCode == 13)) {
    //loop through all values...
    let runChange = false;
    $(".leg").each(function(i, el) {
      if (runChange) {
        $(this).val(++value); //assign new value..
        $(this).trigger("change") //call your change event to handle further...
      }
      if (e.target == el) runChange = true;
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="leg">
<input type="text" class="leg">
<input type="text" class="leg">
<input type="text" class="leg">