# Resizing table widths and making input fields

I am trying to simplify my code, which will do several things:

1. Give the same width to every columns no matter how many columns the table has.
2. Add input field if there is no text inside a td
3. Make sure the input field is no wider than its table cell
4. Make sure, if the input field has size attribute, the input field size will increase based on the size attribute
5. If the table width is too narrow, increase if necessary

My HTML structure:

<table class='test' width='500'>
<tr>
<td>
<span>cell 1</span>
</td>
<td>
<span><input size='18'/></span>
</td>
<td>
<span>cell 3</span>
</td>
</tr>
<tr>
<td>
<span>cell 4</span>
</td>
<td>
<span><input size='15'/></span>
</td>
<td>
<span><input size='15'/> </span>
</td>
</tr>

</table>


jQuery:

$(".test td").each(function(){ columns =$(this).parent().find('td').length;
inputField= $(this).find('input') tdWidth=$(this).width() - 35;
inputSize = $(this).find('input').attr('size'); span =$(this).find('span');
oldTableWdith = $(this).closest('table').attr('width'); if($.trim($(span).html()) == '&nbsp;'){$(span).html("<input type='text' style='width:" + tdWidth + "px;'></input>");
}

inputWidth = inputSize * 11;
inputField.css('width',inputWidth);

if(tableWidth < (columns * inputWidth + 50)){
tableWidth = columns * inputWidth + 50;
}
if(tableWidth===0){
tableWidth = oldTableWdith
}
\$(this).closest('table').width(tableWidth);
})


The code works, but I feel like I can greatly reduce it and achieve what I need. I also need the span tag because I need them to do some other functions. Can anyone help me simplify the code?

## migrated from stackoverflow.comOct 30 '13 at 0:33

This question came from our site for professional and enthusiast programmers.

• one huge efficiency improvement is only test first row for number of columns. Checking how many cells in row...for every td is a massive duplication of effort. Same with setting the table width...you are setting it every time a td is checked. If it was me I would rip whole thing apart and start with top level issues...before checking each td – charlietfl Oct 30 '13 at 0:30
• Make sure you have tried to do all you can about widths using just CSS before you start setting widths with JavaScript. – 200_success Oct 30 '13 at 2:36