I am trying to simplify my code, which will do several things:
- Give the same width to every columns no matter how many columns the table has.
- Add input field if there is no text inside a
td
- Make sure the input field is no wider than its table cell
- Make sure, if the input field has size attribute, the input field size will increase based on the size attribute
- 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()) == ' '){
$(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?