Home > Software engineering >  Display null in ajax show value
Display null in ajax show value

Time:09-18

I've setup a jQuery add/update/delete table which uses ajax calls to controller. Some of the data fields are null.

Is there a way to write this JavaScript code to show empty value if database value returned is null?

Here's the ajax call to the controller, with the data returned to complete the table.

null

let html = ''  
'<tr>' 
'<td class="fw-normal">' data.id '</td>' 
'<td class="fw-normal">' data.employment_type '</td>' 
'<td class="fw-normal">' data.start_date '</td>' 
'<td class="fw-normal">' data.end_date '</td>' 
'<td class="fw-normal">' data.state '</td>' 
'<td class="fw-normal">' data.city '</td>' 
'<td>' 
'<form action="' data.delete_url '" method="post">' 
'@csrf' 
'@method('DELETE')' 
'<div class="btn-group">' 
'<a href="' data.edit_url '" class="btn btn-info btn-sm">ویرایش</a>' 
'<button type="submit" class="btn btn-danger btn-sm job-destroy">حذف</button>' 
'</div>' 
'</form>' 
'</td>' 
'</tr>';
$('#showJobs').append(html);

Note: I want to did not show ward of null.

CodePudding user response:

Consider the following example code.

function checkNull(string) {
  if (string === null) {
    string = ""
  }
  return string;
}

function addRow(data) {
  var row = $("<tr>");
  $.each(data, function(key, value) {
    if (key != "delete_url" || key != "edit_url") {
      $("<td>", {
        class: "fw-normal"
      }).html(checkNull(value)).appendTo(row);
    }
  });
  $("<td>").appendTo(row);
  $("<form>", {
    action: data.delete_url,
    method: "post"
  }).appendTo($("td:last", row));
  $("<div>", {
    class: "btn-group"
  }).appendTo($("form", row));
  $("<a>", {
    href: data.edit_url,
    class: "btn btn-info btn-sm"
  }).html("ویرایش").appendTo($(".btn-group", row));
  $("<button>", {
    type: "submit",
    class: "btn btn-danger btn-sm job-destroy"
  }).html("حذف").appendTo($(".btn-group", row));
  return row;
}

$('#showJobs').append(addRow(myData));

If you add some small functions, you can easily use them to ensure that null does not appear in your HTML.

  • Related