How to select each row and highlight / unselect each row and highlight from data api call

Viewed 202

This is my table on start

<div class= "col-md-7" id = "recyclable-list" >
            
                                <table class="table">
                                <thead>
                                  <tr>
                                    <th style=" padding-left:25px;";>RecyclableID</th>
                                    <th style=" padding-left:100px;">Name</th>
                                    <th style=" text-align: center;">RecyclableType</th>
                                  </tr>
                                </thead>
                                <tbody id="recycleTable">

                                </tbody>
                                
                              </table>  

This is my script call for database

var myarray = [];


                            $.ajax({
                            
                                url:"https://ecoexchange.dscloud.me:8080/api/get",
                        
                                method:"GET",
                                // In this case, we are going to use headers as
                                headers:{
                                    // The query you're planning to call
                                    // i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
                                    query:"RecyclableGet(0)",
                                    
                                    // Gets the apikey from the sessionStorage
                                    apikey:sessionStorage.getItem("apikey")
                                },
                    
                                success:function(data,xhr,textStatus) {
                                
                                myarray = data;
                                buildTable(myarray);
                                console.log(myarray);
                                

                                },

                                error:function(xhr,textStatus,err) {
                                    console.log(err);
                                }
                            });

                            function buildTable(data){
                                var table = document.getElementById("recycleTable")

                                for(var i = 0; i < data.length; i++){
                                    var row = `<tr>
                                                <td>${data[i].RecyclableID}</td>
                                                <td>${data[i].Name}</td>
                                                <td>${data[i].RecyclableType}</td>
                                        </tr>`

                                        table.innerHTML += row
                                        
                                }
                            };
                            

This is my hightlight Js file

$( document ).ready(function() {
     $("#recyclable-list").on('click',function() {
      var selected =  $('#recycleTable tr').on('click',async function(){
         await $('#recycleTable tr').removeClass('highlight');
        $(this).addClass('highlight');
         
        });

        $("#edit").prop('disabled',false);
        $("#edit").removeClass('btn btn-secondary');
        $("#edit").addClass('btn btn-primary');
        $("#delete").prop('disabled',false);

      if (!selected)
      $(this).find('#recycleTable tr').addClass("highlight") & $('#recycleTable tr').removeClass('highlight');
    
        else 
        $("#edit").prop('disabled',true) & $("#delete").prop('disabled',true) & $("#edit").removeClass('btn btn-primary') & $("#edit").addClass('btn btn-secondary');;
        
        
    });
  });

and this is my css style for highlight

    .recycleTable.highlight{
         background-color: #ddd;
        }

But however the highlight now is selecting the whole table row instead of row by row, does anyone have any idea how to i change it to select row per row instead of the the whole row ?

row selected the whole table instead

Now the selected whole table have been fix but however i am unable to unselect the row i choose and button is not enabled when selected a row

row selected but cant un select

3 Answers

Click event on tbody? not a good idea, i suggest you to change your code to this :

...
$("#recyclable-list").on('click',function() {
  var selected = $(this).find('#recycleTable').hasClass("highlight");
  ...
  if (!selected)
    $(this).find('#recycleTable').addClass("highlight");
...

You care calling id but your declaration is a class. Change from . to # as in #recycleTable.highlight

Update

Dynamically added <tr> must have the "click" event delegated to a parent element that's been there since the DOM was loaded (ie hard coded in HTML). In this case the <tbody> is a good canident. One extra parameter is needed:

/*
'tr' delegates click events to any <tr> within
the <tbody> whether static or dynamic.
*/
$('tbody').on('click', 'tr', function(e) {...

First of all, never use #id, use class, otherwise you have hindered your code -- that's especially true if you are using jQuery. #id is useful in circumstances such as Bootstrap plugins, but not much else. The example below uses only classes.

This will allow only a single <tr> to be highlighted and also removes highlighting if the <tr> was already highlighted.

$('tbody tr').not($(this)).removeClass('highlight');
$(this).toggleClass('highlight');

This will disable the <button>s if there's a highlighted <tr>

const btns = $('.btn-group button');
...
if ($(this).hasClass('highlight')) {
  btns.prop('disabled', false).removeClass('disabled dark');
} else {
  btns.prop('disabled', true).addClass('disabled dark');
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .highlight {
      background-color: #ddd;
    }
    
    button {
      display: inline-block;
      width: 100px;
    }
    
    .dark {
      background-color: #000;
      color: #666;
    }
  </style>
</head>

<body>
  <main class="fluid-container">
    <fieldset class='btn-group'>
      <button class='add btn btn-success'>Add Row</button>
      <button class='dark edit btn btn-primary disabled change-row' disabled>Edit</button>
      <button class='type btn btn-warning'>Add Type</button>
      <button class='dark delete btn btn-danger disabled change-row' disabled>Delete</button>
    </fieldset>
    <table class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>User Name</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </main>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script>
    const buildTable = data => {
      const table = document.querySelector('.table tbody');

      for (let i = 0; i < data.length; i++) {
        let row = `<tr>
    <td>${data[i].name}</td>
    <td>${data[i].username}</td>
    <td>${data[i].email}</td>
    </tr>`;
        table.insertAdjacentHTML('beforeEnd', row);
      }
    };

    const getData = async(url) => {
      const response = await fetch(url);
      const json = await response.json();
      return buildTable(json);
    };
  getData('https://jsonplaceholder.typicode.com/users/');

    $(document).ready(function() {
      const btns = $('.change-row');
      $("tbody").on('click', 'tr', function(e) {
        /* //Add this line if you want only a single row selected
    
        $('tbody tr').not($(this)).removeClass('highlight');
        */
        $(this).toggleClass('highlight');

        if ($('tbody tr').hasClass('highlight')) {
          btns.prop('disabled', false).removeClass('disabled dark');
        } else {
          btns.prop('disabled', true).addClass('disabled dark');
        }

      });
    });
  </script>
</body>

</html>

Related