I have a table having 15 rows of text boxes with ids text1, text2 … text15 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.
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>