简体   繁体   中英

HTML Table Rowspan Conditional

i have this html table Which has a "User Id" column with some of the same values. I want to do a merge for the same values using rowspan.

在此处输入图像描述

However, the data I have is dynamic data so I don't want to write rowspan="(number)". The output i want is to merge the same number in "User Id" dynamically like this:

在此处输入图像描述

Can anyone help?

I can understand what you are trying to do actually. That can be done in several ways. Conditioning rowspan is also possible with a little bit of complex logic. But I would go with the simplest way. Example:

I don't know which server-side language you are using;assuming that you are using PHP. So,

Firstly, just write two functions. 1st for fetching the "User IDs" from your database table. And 2nd for fetching user data against the user id.

<?php 
function user_ids(){
    $stmt = $conn->prepare("SELECT `user_id` FROM `table` GROUP BY user_id);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $result;
}

function user_ids($user_id){
    $stmt = $conn->prepare("SELECT *FROM `table` WHERE user_id = ?);
    $stmt->execute(array($user_id));
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}

$user_ids = user_ids();
foreach($user_ids as $data){
?> 
<tr>
   <td><?= $data['user_id'] ?></td>
   <td>
      <table>
         <?php
          $user_data = user_data($data['user_id']);
          foreach($user_data as $x){ ?>
          <tr>
            <td><?= $x['id'] ?></td>
            <td><?= $x['title'] ?></td>
            <td><?= $x['body'] ?></td>
          </tr>
         <?php } ?>
      </table>
   </td>
</tr>

<?php 
} 
?>

Some Js is required for accomplishing this task -

  let presentElem = {};
  let removedElem = [];
  const rows = document.getElementsByTagName("tr");
  Array.from(rows).forEach(element => {
    if (presentElem[element.innerText.charAt(0)]){ 
      element.deleteCell(0);
      removedElem.push(element.firstChild)
    }
    else presentElem[element.innerText.charAt(0)] = element.firstChild;
  })
  Object.keys(presentElem).forEach(element => {
    presentElem[element].setAttribute("rowspan", removedElem.length )
  })

This code will add this functionality all tables present in the document if you don't want that add a custom class to all the tr tags in the table and then assign the value of constant rows to document.getElementsByClassName("classname") and this will only add this functionality to this table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM