skip to Main Content

I want to change the <tr> color when I click the <td> inside of it and remove the color when I click on another <td> in the same table (I have multiple tables) ? The problem is I already have a onclick function that I need.

here is my html:

<table class="table table-sm mb-0">
 <thead>
  <tr>
   <th scope="col">Plant</th>
   <th scope="col">Location</th>
   <th scope="col" class="text-center">Total Pallet</th>
  </tr>
 </thead>
 <tbody id="rows">
 </tbody>
</table>

here is my JS:

$.each(data, function (key, value) {
 html += "<tr>"
  + "<td>" + value["plant_name"] + "</td>"
  + "<td>" + value["loc_name"] + "</td>"
  + "<td class='pointer text-center' onclick='getModelData("" + value["werks"] + "", "" + value["lgort"] + "")'><u>" + value["total"] + "<u></td>"
  + "</tr>";
});

$("#rows").html(html);

I have tried adding another function inside the onclick but there is no result

function getOtherData() {
  var row = $(this);

  row.css('background-color', 'red');
}

2

Answers


  1. To be able to set the parent tr of the clicked element to have a red background the event handler you bind must be able to get a reference to that element. Using onX attributes do not get this out of the box – you need to pass the element as an argument manually. This is part of the reason they are not good practice and should be avoided.

    Also note that there are several other things you can do to improve the quality of your code, such as using map() and a template literal to build your HTML which should be appended to the table, using CSS to style the UI instead of the <u> element, using classes to dynamically update the UI instead of explicitly setting style on the element itself and finally adding unobtrusive event handlers.

    Here’s a working example with all the above amendments made. Note the use of data attributes instead of passing arguments in the onclick attribute.

    const data = [
      { plant_name: "plant_name 1", loc_name: "loc_name 1", lgort: "lgort 1", werks: "werks 1", total: "total 1" },
      { plant_name: "plant_name 2", loc_name: "loc_name 2", lgort: "lgort 2", werks: "werks 2", total: "total 2" },
      { plant_name: "plant_name 3", loc_name: "loc_name 3", lgort: "lgort 3", werks: "werks 3", total: "total 3" },
      { plant_name: "plant_name 4", loc_name: "loc_name 4", lgort: "lgort 4", werks: "werks 4", total: "total 4" }
    ]
    
    let html = data.map(obj => `
      <tr>
        <td>${obj.plant_name}</td>
        <td>${obj.loc_name}</td>
        <td class="pointer text-center" data-werks="${obj.werks}" data-lgort="${obj.lgort}" data-total="${obj.total}">${obj.total}</td>
      </tr>`);
    
    $("#rows").html(html);
    
    $('td.pointer').on('click', e => {
      const $td = $(e.target);
      const $tr = $td.closest('tr');
      $('.highlight').not($tr).removeClass('highlight');
      $tr.toggleClass('highlight');
      
      // read model data:
      console.log($td.data('werks'));
      console.log($td.data('lgort'));
      console.log($td.data('total'));
    });
    table {
      border-collapse: collapse;
    } 
    
    td {
      padding: 5px;
    }
    
    td.pointer {
      text-decoration: underline;
    } 
    
    tr.highlight {
      background-color: #F00;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <table class="table table-sm mb-0">
     <thead>
      <tr>
       <th scope="col">Plant</th>
       <th scope="col">Location</th>
       <th scope="col" class="text-center">Total Pallet</th>
      </tr>
     </thead>
     <tbody id="rows">
     </tbody>
    </table>
    Login or Signup to reply.
  2. Simply bind another click event on your td and remove all background before adding new background to clicked item. See the following example.

    var data = [
        { "plant_name": "Plant 1", "loc_name": "Loc 1", "total": "10", "werks": "1" },
        { "plant_name": "Plant 2", "loc_name": "Loc 2", "total": "10", "werks": "2" },
        { "plant_name": "Plant 3", "loc_name": "Loc 3", "total": "10", "werks": "3" },
        { "plant_name": "Plant 4", "loc_name": "Loc 4", "total": "10", "werks": "4" },
        { "plant_name": "Plant 5", "loc_name": "Loc 5", "total": "10", "werks": "5" }
    ];
    
    var html = "";
    $.each(data, function(key, value) {
      html += "<tr>" +
        "<td>" + value["plant_name"] + "</td>" +
        "<td>" + value["loc_name"] + "</td>" +
        "<td class='pointer text-center' onclick='getModelData("" + value["werks"] + "", "" + value["lgort"] + "")'><u>" + value["total"] + "<u></td>" +
        "</tr>";
    });
    
    $("#rows").html(html);
    
    $("td").off("click").on("click", function() {
      $(this).closest("tbody").find("tr").css('background-color', '')
      getOtherData($(this).closest("tr"));
    });
    
    function getOtherData(target) {
      target.css('background-color', 'red');
    }
    
    function getModelData(val) {
      console.log(val);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table class="table table-sm mb-0">
      <thead>
        <tr>
          <th scope="col">Plant</th>
          <th scope="col">Location</th>
          <th scope="col" class="text-center">Total Pallet</th>
        </tr>
      </thead>
      <tbody id="rows">
      </tbody>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search