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

How to use jQuery to set a value in all following rows of a table?

I have a table having 15 rows of text boxes with ids text1, text2text15 etc.

If I write something suppose in the 5th text box I want the same text to be written in all subsequent boxes i.e the 6th, 7th, 8th … 15th.

The following code has done the job but only for the first textbox. I want it for any textboxes.

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

How can I modify the code to achieve the goal?

$(document).ready(function() {
  i = 1;
  var iki = i + 1;
  
  $('#text' + i).keyup(function() {
    for (var k = iki; k <= 15; k++) {
      $('#text' + k).val($(this).val());
    }
  });
});

>Solution :

To do what you require place a common class on all your input elements. This will make them much easier to select. I’d also suggest removing the incremental id attributes as they are an anti-pattern which makes code more complex than it needs to be.

Once you’ve attached the event handler you can use the Event passed to the handler to retrieve the element which caused the event. From there you can use DOM traversal to find the nearest tr element, and all following tr, before updating the input elements within them.

jQuery($ => {
  $('.foo').on('input', e => {
    $(e.target).closest('tr').nextAll('tr').find('.foo').val(e.target.value);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<table>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
  <tr><td><input type="text" class="foo" /></td></tr>
</table>
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