jQuery get table width of cells and assign the same to different table of same location/index

235
September 18, 2017, at 06:29 AM

I have started learning jQuery, but weak with syntax as of now.

I have two table's as below:-

<table class="tableone">
  <thead>
    <th width="30px">ID</th>
    <th width="150px">NAME</th>
    <th width="100px">Age</th>
  </thead>
</table>
<table class="tabletwo">
  <tbody>
    <td>1</td>
    <td>John</td>
    <td>32</td>
  </tbody>
</table>

Where tableone has some dynamic width at run time. I need to get the width of column and assign the same to tabletwo same column index.

so, that after the code run's the HTML should be like :-

<table class="tabletwo">
  <tbody>
    <td width="30px">1</td>
    <td width="150px">John</td>
    <td width="100px">32</td>
  </tbody>
</table>

I was trying the same using jQuery where I was trying to loop thru the rows and get the width. While doing so, I can capture the index of the column and access the tabletwo. But I am not sure about the syntax.

$(document).ready(function() {
  /* looping into the th*/
  $("table.tableone thead").find('th').each(function(index,value) {
    console.log(index);
    console.log(value);
  })   
});
Answer 1
(function(){
    var temp=$("table.tabletwo td");
    $("table.tableone th").each(function(i,v) {
        temp[i].width=v.width;
    });
})();
Answer 2

Here it is:

var firstTableWidth = []; 
 
$('.tableone th').each(function(i, item) { 
  firstTableWidth.push($(this).attr("width")); 
}) 
 
$('.tabletwo td').each(function(i, item) { 
  $(this).attr("width", firstTableWidth[i]); 
})
td { 
  text-align: center; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<table class="tableone"> 
  <thead> 
    <th width="30px">ID</th> 
    <th width="150px">NAME</th> 
    <th width="100px">Age</th> 
  </thead> 
</table> 
<table class="tabletwo"> 
  <tbody> 
    <td>1</td> 
    <td>John</td> 
    <td>32</td> 
  </tbody> 
</table>

You can inspect the second table and be sure, that all width attributes were applied properly. And I have added one CSS rule:

td {
  text-align: center;
}

It will center text of td's in second table as it centered in first.

Rent Charter Buses Company
READ ALSO
Database design for statistics of views/likes/downloads?

Database design for statistics of views/likes/downloads?

So i am trying to work out a database design to keep track of views, likes and downloadsNow the amount of entries to keep track of is expected to be 1m or more, so normally i would just track each entry daily, but with 1m i am having concerns about performance...

180
Using 2 &ldquo;Group By&rdquo; in one SQL Query

Using 2 “Group By” in one SQL Query

I got 3 tables that look like this:

176