Frank Lehmann
Frank Lehmann

Reputation: 1

Jquery td cell width always 0

i have this table created. This table should have same column width for the whole table. If the cells have different values, so the table normaly grows. But i want the table to have identical columns within a given table width.

Example: The screen is created in 2 segments, left and right. The right segment has the table, but the width of this segment is greater than the table width. So i can calculate every column with the same width value to show this table with same column width.

Looks like this

  Posart   |   Datum    |
1234567890 | 1234567890 |
   1234    | 12.12.2019 |

<table  id="Auftragspositionen" class="standardliste" summary="">
<tr><th id="Posart">Posart</th><th id="Datum">Datum</th>
</tr>
<tr>
<td headers="Posart"><div class="left noborder">001.00<br/>Z <br/>Zeit</div></td>
<td headers="Datum"><div class="middle noborder">12.03.2018</div></td>
</tr></table>

And my jQuery select is this !

b2=$('#Auftragspositionen');
b2.find("tr th").children("td").each(function(i) {
        tdWidth = $(this).width();
        alert(i + 'td width is ' + $(this).tdWidth);
        });

My question is, that every cell td width=0 ??? Why it is ?

Upvotes: 0

Views: 283

Answers (1)

acdcjunior
acdcjunior

Reputation: 135762

Observe this part of your code:

tdWidth = $(this).width();                     // here you define the tdWidth variable
alert(i + 'td width is ' + $(this).tdWidth);

In the second line, instead of accessing the tdWidth variable you just created, when you use $(this).tdWidth you actually try to access a jQuery property called tdWidth which doesn't exist.

So the solution is to really access your variable (lose the $(this). there). Also it is better to declare the variable locally, using var.

var tdWidth = $(this).width();         // using var here
alert(i + ' td width is ' + tdWidth);  // not $(this).tdWidth !

For the demo below I changed the selector as well (from b2.find("tr th") to b2.find("tr"), because the former finds ths that are children of tr and ths have no tds children - which is what you search later with .children("td")):

b2 = $('#Auftragspositionen');
b2.find("tr").children("td").each(function(i) {
  var tdWidth = $(this).width();
  alert(i + ' td width is ' + tdWidth);
});
table, tr, th, td { border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Auftragspositionen" class="standardliste" summary="">
  <tr>
    <th id="Posart">Posart</th>
    <th id="Datum">Datum</th>
  </tr>
  <tr>
    <td headers="Posart">
      <div class="left noborder">001.00<br/>Z <br/>Zeit</div>
    </td>
    <td headers="Datum">
      <div class="middle noborder">12.03.2018</div>
    </td>
  </tr>
</table>

Upvotes: 1

Related Questions