Search code examples
javascriptjqueryhtml-tabledynamic-sizing

Textboxes matching table column width


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


Solution

  • 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;
        });
    });