I have this table with a textbox for each column (they are going to be used for filtering). The textboxes should be the same width as the corresponding column.
This is as far as I've gotten (simplified version): http://jsfiddle.net/9uUpP/
Pseudo-code explaining what I am trying to do with my current script:
document ready{
var index = 0;
for each(th){
textboxNr(index).width = this.width;
index++;
}
}
As you can see, the textboxes doesn't match the columns in width.
important: The table + content is generated and may change from time to time, so I have to make a dynamic solution. The number of columns will always be the same, but their width may change
First child will not be 0th child. So index should be 1 initially.
Look here . It says children index starts with 1.
Then px
is not needed in width, just the value does enough. Check here
Here is the updated working jsFiddle
Your code should be,
$(document).ready(function () {
var index = 1;
$("#table th").each(function () {
$('input[type="text"]:nth-child('+index+')').css('width',$(this).width());
index = index+1;
});
});
There's no need of an extra variable for this, you can use the index
parameter in the each
method itself, along with the :eq() Selector
like:
$(document).ready(function () {
$("#table th").each(function (index) {
$('input[type="text"]:eq(' + index + ')').css('width', $(this).width());
});
});
I have used :eq()
here instead of :nth-child(n)
since :nth-child(n)
uses 1-based indexing to conform to the CSS specification but the index
parameter in the each
method starts from 0
and :eq()
use 0-based indexing.
I believe the indexes were incorrect...
$(document).ready(function () {
$("#table th").each(function (i, v) {
$('input[type="text"]:nth-child(' + (i+1) + ')').css('width', $(this).width() + 'px');
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.