sparpo
sparpo

Reputation: 109

How to select a row in a html table without using a button?

Okay so i have a large html table(over 120 rows) and a search bar. The problem is that these rows dont have buttons in them and i want the user to be able to select them. I got this data from an internet database. I dont want to have to go through 120 rows of html table putting a button in each one(also im only working with a section of the original table which has over 3000 rows, so going through all of it is really not an option). Anyway how can i make the user able to select a cell/row and get its value without changing the original table in html?

Upvotes: 1

Views: 15824

Answers (2)

lhavCoder
lhavCoder

Reputation: 961

you can always put have a click event on the td/tr and do whatever you want the function which get called

var elements= document.getElementsByTagName('td');
for(var i=0; i<elements.length;i++)
{
(elements)[i].addEventListener("click", function(){
   alert(this.innerHTML);
});
}
td:hover{
background-color:gray;
cursor:pointer;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>[email protected]</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>[email protected]</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>[email protected]</td>
      </tr>
    </tbody>
  </table>

Upvotes: 8

Davide Capodaglio
Davide Capodaglio

Reputation: 143

If you want to "select" a cell or a row without adding other controls to the table you could add an onclick handler and do something inside it (for example, change its background color, print a message, or anything you want)

Upvotes: 0

Related Questions