Home > Back-end >  Show / Hide button base on column value
Show / Hide button base on column value

Time:10-14

I have a Grid View where i have 2 columns (FOOD and OPERATIONS). In FOOD column I am showing my menu. In OPERATIONS column, I have 2 buttons (DELETE and EDIT). What I want is if FOOD is "HAMBURGER" I want the two buttons to be visible, otherwise I want to hide them. Here is the demonstration of what I want

I have tried this code in jQuery. But I don't think if the condition implementation is correct.

Menu = $('#tblMenu').DataTable({
        columns: [
            { "data": "FOOD", responsivePriority: 1, "searchable": true },
            {
                "data": null,
                render: function (data, type, row) {
                    btn = '<div >';
                    btn  = '<a  href="/editMenu?id='   row.idOrder   '\">EDIT</a>';
                    btn  = '<a  id="deleteMenu" href="/deleteMenu?id='   row.idOrder   '\">DELETE</a>';
                    
                    //Condition
                    if (data.find("FOOD") != "HAMBURGER") {
                        /*btn  =*/ $('<a  href="/editMenu?id='   row.idOrder   '\">EDIT</a>').hide();
                        $('<a   href="/deleteMenu?id='   row.idOrder   '\">DELETE</a>').hide();
                    } else {
                        $('<a  href="/editMenu?id='   row.idOrder   '\">EDIT</a>').show();
                        $('<a   href="/deleteMenu?id='   row.idOrder   '\">DELETE</a>').show();
                    }

                    btn  = '</div>';
                    return btn;
                }, 
            }
        ]
    });
    
//HTML
<table  style="font-size:75%; " id="tblMenu">
    <thead >
        <tr>
            <th >FOOD</th>
            <th >OPERATIONS</th>
        </tr>
    </thead>
</table>

CodePudding user response:

The question was changed few moments after I finished crafting this demo. So this answer doesn't perfectly fit the scenario with the datatables.net but yet it gives hints on a strategy you could implement.

In your latest code you are trying to evaluate a condition based on the input data and crafting some elements on the fly to fill the table.

You could yet have a second column containing the buttons on each single row but just show/hide that cell based on the existence of a given class in that row.

Here on document ready I'm looping through all the table rows and if the value Hamburger is found on the first cell, to the whole rows we add the class enabled. Such condition will trigger the css rule styling that cell as visible opposed to hidden.

$(document).ready(function () {
  //for each row in the table
  $('table.foods > tbody > tr').each((i,row)=>{
    //grabs the text value from the first cell in the row,
    const foodValue = $(row).find('td:first-child').text();    
    //and if it's hamburger,
    if(foodValue == 'Hamburger'){
      //adds the class enabled to the row
      $(row).addClass('enabled');
    }      
  });
});
/**************************************************************
 * Styles to show/hide rows having/not having the enabled class
 **************************************************************/

table.foods > tbody > tr > td:nth-child(2) {
  visibility: hidden;
}

table.foods > tbody > tr.enabled > td:nth-child(2) {
  visibility: visible;
}

/**************************************************************
 * Styles for better presentation
 **************************************************************/

table.foods {
  border-collapse: collapse;
  width: 100%;
}

table.foods th {
  text-align: center;
}

table.foods td,
table.foods th {
  border: solid 2px black;
  padding: 1rem;
}

.action {
  border: solid 2px;
  border-radius: 5px;
  padding: .5rem 1rem;
  background: white;
}

.edit {
  border-color: red;
  color: red;
}

.delete {
  border-color: blue;
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table >
  <thead>
    <th>FOOD</th>
    <th>DRINK</th>
  </thead>
  <tbody>
    <tr>
      <td>Hamburger</td>
      <td>
        <button type="button" >EDIT</button>
        <button type="button" >DELETE</button>
      </td>
    </tr>
    <tr>
      <td>Pasta</td>
      <td>
        <button type="button" >EDIT</button>
        <button type="button" >DELETE</button>
      </td>
    </tr>
    <tr>
      <td>Pizza</td>
      <td>
        <button type="button" >EDIT</button>
        <button type="button" >DELETE</button>
      </td>
    </tr>
  </tbody>
</table>

CodePudding user response:

I noticed that DataTables is being used as well as Bootstrap. I assumed that OP has BS4 since DataTables has yet to have a stylesheet for BS5. See Figure I for the list of external files loaded for the example.

Figure I

  • bootstrap.min.css v4.6.1
  • dataTables.bootstrap4.min.css v1.10.21
  • jquery.min.js v3.6.1
  • popper.min.js v1.16.1
  • bootstrap.bundle.min.js v4.6.1
  • jquery.dataTables.min.js v1.10.21

In the dataTable() plugin, columnDefs parameter and render: function() property were used to resolve the problem. See Figure II.

Figure II

{
  targets: 1, // This is rendering buttons in the second column
  data: null, // This uses the whole source (dataSet)
  render: function(data, type, row, meta) {
    /**
     * If data.item (OP: data.FOOD) is not "CONFIGURABLE" (OP: "HAMBURGER")...
     * >status< = "hidden" otherwise it's = "" (nothing)
     */
    let status = data.item !== "CONFIGURABLE" ? "hidden" : "";
    /**
     * Only a single string is needed. Note that >status< is a class 
     * (see CSS in example). It's important that the "hidden" class is
     * added to your CSS exactly how it is in the example CSS. BS styles
     * are difficult to override so if changed it may not work.
     */
    const btn = `
      <div >
        <a href="/editMenu?id=${row.idOrder}" >EDIT</a>
        <a href="/deleteMenu?id=${row.idOrder}" >DELETE</a>
      </div>`;
      return btn;
    }
  }

const dataSet = [{item:0, config:""}, {item:"CONFIGURABLE", config:""},{item:2, config:""},{item:"CONFIGURABLE", config:""},{item:4, config:""},{item:5, config:""},{item:"CONFIGURABLE", config:""},{item:7, config:""},{item:"CONFIGURABLE", config:""},{item:8, config:""},{item:9, config:""},{item:"CONFIGURABLE", config:""}];

const Menu = $('#tblMenu').DataTable({
  data: dataSet,
  columns: [{
    title: "Item"
  }, {
    title: ""
  }],
  columnDefs: [{
      targets: 0,
      data: "item"
    },
    {
      targets: 1,
      data: null,
      render: function(data, type, row, meta) {
        let status = data.item !== "CONFIGURABLE" ? "hidden" : "";
        const btn = `
          <div >
            <a href="/editMenu?id=${row.idOrder}" >EDIT</a>
            <a href="/deleteMenu?id=${row.idOrder}" >DELETE</a>
          </div>`;
        return btn;
      }
    }
  ]
});
.btn-group.hidden {
  display: none;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet">
  <style></style>
</head>

<body>
  <main >
    <section >
      <div >
        <table id="tblMenu"  style="font-size:75%;">
          <thead >
            <tr>
              <th ></th>
              <th ></th>
            </tr>
          </thead>
        </table>
      </div>
    </section>
  </main>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>

  <script></script>
</body>

</html>

CodePudding user response:

Can you show us more of your code? You are using jQuery here,

//Sets your ready function    
$(document).ready(function () {

                $("#Delete").click(function () {

                    $("a").hide(); //Selecting the <a> and hiding it on click
                });
                $("#show").click(function () {
                    $("a").show();//Selecting the <a> and showing it on click



                });
            });

Please update more on your question of what you are trying to achieve, you are currently select to all instance of element, not though, use

$("#a").show(); // ID based
$(".a").show(); //Selecting with class names
  • Related