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());
}
});
});
2
Answers
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 incrementalid
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 followingtr
, before updating theinput
elements within them.While you’ve already accepted an answer, I thought I’d offer a non-jQuery alternative, which should function perfectly well in your own use-case as well.
The examples are below, with explanatory comments in the JavaScript:
JS Fiddle demo.
There is the potential that you may need to work with specific
<input>
elements based on the column that they’re in; if that’s the case then the following should achieve your aims:JS Fiddle demo.
References:
Array.prototype.filter()
.Array.prototype.forEach()
.Array.prototype.map()
.Array.prototype.slice()
.document.querySelector()
.document.querySelectorAll()
.Element.closest()
.Element.querySelector()
.Element.querySelectorAll()
.EventTarget.addEventListener()
.HTMLTableCellElement
.HTMLTableRowElement
.