How to retrieve values ​​of unselected rows in HTML data table using jquery
P粉431220279
P粉431220279 2024-04-05 09:26:49
0
1
1422

I'm trying to get the value of all rows where the button was not clicked. For example, when I click a button on the first row, I want to retrieve the value of the row that was not clicked.

 
var table = document.getElementById("all_department");
if (table != null) {
  for (var i = 0; i < table.rows.length; i++) {
  table.rows[i].onclick = function() {
  tableText(this);
      }
    }
  }    
    
function tableText(tableRow) {
var myJSON = JSON.stringify(tableRow);
console.log(myJSON);
}
    <table id="all_departments">
     <thead>
              <th><button>click</button></th>                                   
              <th>Departments</th>
              <th>Creation Date</th>
              <th>Name</th>
     </thead>
    <tbody class="bl">
           <tr>
                <td><button>click</button></td>
                <td>Management</td>
                <td>2-3-2016</td>
                <td>client x</td>
          </tr>
    
           <tr>
                <td><button>click</button></td>
                <td>Sales</td>
                <td>25-6-2019</td>
                <td>client y</td>
          </tr>
    </tbody>
    </table>

P粉431220279
P粉431220279

reply all(1)
P粉561323975

You can listen to the click handler on the button, get the parent tr of the clicked button, and then get the sibling button.

Once we have all siblings we can loop through them and form our resulting string.

Please refer to the code below

const allBtns = document.querySelectorAll('button');
allBtns.forEach(function(btn) {
  btn.addEventListener('click', function(e) {
    let elem = this.closest('tr');
    const siblings = getSiblings(elem);
    const result = [];
    siblings.map(ele => {
      ele.querySelectorAll('td').forEach((e, i) => {
        if (i !== 0) {
          result.push(e.innerText);
        }
      });
    });
    console.log(result.join(','));
  })
});

const getSiblings = function(e) {
  let siblings = [];
  if (!e.parentNode) {
    return siblings;
  }

  let sibling = e.parentNode.firstChild;

  while (sibling) {
    if (sibling.nodeType === 1 && sibling !== e) {
      siblings.push(sibling);
    }
    sibling = sibling.nextSibling;
  }
  return siblings;
};

Departments Creation Date Name
Management 2-3-2016 client x
Sales 25-6-2019 client y
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!