Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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">

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading