Is this possible? I’m trying to hide the Approve Button if the column approvedby
is not empty. This is from a Server-Side dataTable. My problem is I can’t find a way for if else to be used because I’m using return ""
.
This is the script.
$(function() { $('#example').DataTable( { dom: "Bfrtip", ajax: { url: "earnings_amendment_account_table.php", type: "POST" }, serverSide: true, columns: [ { data: "accountcode" }, { data: "accounttitle" }, { data: "accounttype" }, { data: "approvedby" }, { "data": "accountcode", "name": " ", "autoWidth": true, "render": function (data, type, full, meta) { return "<button class='btn btn-success btn-sm btn-flat edit' data-id='"+full.accountcode+"'><i class='fa fa-edit'></i> Edit</button> <button class='btn btn-danger btn-sm btn-flat delete' data-id='"+full.accountcode+"'><i class='fa fa-trash'></i> Delete</button> if (empty("+full.approvedby+")) { <button class='btn btn-warning btn-sm approve btn-flat' data-id='"+full.accountcode+"'><i class='fa fa-check-square-o'></i> Approve</button>}";} } ], select: false, buttons: [] } ); } );
This is the result. I can’t seem to find a way for if else
to work inside return ""
.
Advertisement
Answer
Try this
$(function() { $('#example').DataTable( { dom: "Bfrtip", ajax: { url: "earnings_amendment_account_table.php", type: "POST" }, serverSide: true, columns: [ { data: "accountcode" }, { data: "accounttitle" }, { data: "accounttype" }, { data: "approvedby" }, { data: "accountcode", name: " ", autoWidth: true, render: function (data, type, full, meta) { let html = "<button class='btn btn-success btn-sm btn-flat edit' data-id='"+full.accountcode+"'><i class='fa fa-edit'></i> Edit</button> "; html += "<button class='btn btn-danger btn-sm btn-flat delete' data-id='"+full.accountcode+"'><i class='fa fa-trash'></i> Delete</button> "; html += "<button class='btn btn-danger btn-sm btn-flat delete' data-id='"+full.accountcode+"'><i class='fa fa-trash'></i> Delete</button> "; if (!full.approvedby) html += "<button class='btn btn-warning btn-sm approve btn-flat' data-id='"+full.accountcode+"'><i class='fa fa-check-square-o'></i> Approve</button>"; return html; } } ], select: false, buttons: [] } ); } );
Note I removed the empty() function you used in the if statement.
The reason why it didnt work is because you wrote the if statement as a string so it didnt process as a javascript code.
Here’s an example on how to write inline if statements in javascript.
return 'Hello my name is ' + (name === 'Miroslav' ? name : 'Anonymous') + ' and I just wrote an inline if statement';