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

Time:12-05

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

CodePudding user response:

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");
...

CodePudding user response:

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

CodePudding user response:

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');
} else {
  btns.prop('disabled', true).addClass('disabled');
}

Note, that the example just deals with a <table> with <tr> already present and not dynamically created <tr>, but it doesn't matter. Also, the <button>s are wrapped in .btn-group which Bootstrap CSS will style nicely and provides a better selector for the <button>s $('.btn-group button'). Finally, all browsers add a <tbody> to <table> so there's no need to include it in HTML (unless you want more than one <tbody>).

$(document).ready(function() {
  const btns = $('.btn-group button');
  $("tbody tr").on('click', function() {
    $('tbody tr').not($(this)).removeClass('highlight');
    $(this).toggleClass('highlight');

    if ($(this).hasClass('highlight')) {
      btns.prop('disabled', false).removeClass('disabled');
    } else {
      btns.prop('disabled', true).addClass('disabled');
    }
  });
});
.highlight {
  background-color: #ddd;
}

button {
  display: inline-block;
  width: 100px;
}
<!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">
</head>
<body>
  <main class="fluid-container">
    <table class="table">
      <thead><tr><th>RecyclableID</th><th>Name</th><th>RecyclableType</th></tr></thead>
      <tr><td>X</td><td>X</td><td>X</td></tr>
      <tr><td>X</td><td>X</td><td>X</td></tr>
      <tr><td>X</td><td>X</td><td>X</td></tr>
      <tr><td>X</td><td>X</td><td>X</td></tr>
      <tr><td>X</td><td>X</td><td>X</td></tr>
      <tr><td>X</td><td>X</td><td>X</td></tr>
    <tfoot><tr><td colspan='2'></td>
      <td class='btn-group'>
        <button class='edit btn btn-primary disabled' disabled>Edit</button>
        <button class='delete btn btn-danger disabled' disabled>Delete</button>
      </td>
    </td>
    </tfoot>
    </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>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related