I'm building an admin panel from scratch for a personal project, one of the tasks I want it to do is show data in a table, in order to get this data I use AJAX and JQuery to grab data from the server and populate the table in the frontend.
This data has a sent string field (can be string or date-format), issue I have is I want to append a font awesome button ONLY if the field sent is an empty string "" without having to create a different html template inside my success function.
My JQuery code:
$.ajax({
async: true,
url: '/bulletins',
type: 'GET',
dataType: 'JSON',
success: function (data) {
$('.row[data-link=' + linked_entry + ']').remove();
$.each(data.bulletins, function (index, item) {
var subbed_row = '<tr class="row" data-link="subs">';
subbed_row += '<td>' + item.title + '</td>';
subbed_row += '<td>' + item.body + '</td>';
subbed_row += '<td>' + item.sent + '</td>';
subbed_row += '<td class="entry_table_options_container"><i class="fa fas fa-envelope form_show_edit" data-link="subs" data-id="'+ item.id + '" data-title="'+ item.title +'" data-body="'+ item.body +'" data-sent="'+ item.sent +'" title="Enviar boletín a todos los subscriptores" style="background-color:#82C91E;"></i></td>';
subbed_row += '</tr>';
$('.entry_table_container[data-link=' + linked_entry + ']').append(subbed_row);
});
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is the part I want to append or not, in case it's not empty the row would just appear without the button.
subbed_row += '<td class="entry_table_options_container"><i class="fa fas fa-envelope form_show_edit" data-link="subs" data-id="'+ item.id + '" data-title="'+ item.title +'" data-body="'+ item.body +'" data-sent="'+ item.sent +'" title="Enviar boletín a todos los subscriptores" style="background-color:#82C91E;"></i></td>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</div>
The ternary operator is pretty useful for a small inline 'if' condition.
You use it like:
condition ? [result if true] : [result if false]
So in your case, you should be able to do something like this:
subbed_row += data === '' ? '<td class="entry_table_options_container"><i class="fa fas fa-envelope form_show_edit" data-link="subs" data-id="'+ item.id + '" data-title="'+ item.title +'" data-body="'+ item.body +'" data-sent="'+ item.sent +'" title="Enviar boletín a todos los subscriptores" style="background-color:#82C91E;"></i></td>' : ''
If data
is ''
then it will add the td
string to subbed_row
, otherwise it will add nothing (''
).