Search code examples
javascriptjqueryapi

Trouble hiding a div within a template literal using jQuery


I've written this bit of jQuery code in Oxygen Builder's JavaScript element to query the job board API and return an array of departments and their jobs. I'm testing to see if the department[0].jobs.length returns 0 then hide the #job-list div, otherwise show it and its associated jobs. The code succeeds in querying the API and returning 0 jobs but the remainder of the ternary operator will not hide the div.

jQuery(document).ready(function($) {
  $.getJSON('https://boards-api.greenhouse.io/v1/boards/forwardnetworks/departments', postings => {

    $("#div_block-420-61456").html(`
    <div id="job-list">${postings.departments[0].jobs.length == 0 ? $("#job-list").hide() : $("#job-list").show()}<h3 class="dept">${postings.departments[0].name}</h3>
    ${postings.departments[0].jobs.map(item => `<a href="${item.absolute_url}"><h4 class="job-title">${item.title}</h4></a>
    <p class="job-descrip">${item.location.name}`).join('')}</div> `);
  });
});

I generally get a return of [object object]


Solution

  • As I mentioned in the comments, I would add a guard within the .getJSON success handler that will return early if there are no jobs to display.

    The resulting function would be:

    const departmentIndex = 0;
    
    $(function ($) {
      $.getJSON('https://boards-api.greenhouse.io/v1/boards/forwardnetworks/departments', postings => {
        if (postings.departments[departmentIndex].jobs.length === 0) { return; }
    
         $("#div_block-420-61456").html(`
          <div id="job-list">
            <h3 class="dept">${postings.departments[departmentIndex].name}</h3>
            ${postings.departments[departmentIndex].jobs.map(item => `
                <a href="${item.absolute_url}">
                    <h4 class="job-title">${item.title}</h4>
                </a>
                <p class="job-descrip">${item.location.name}`
            ).join('')}
          </div>
        `);
      }); 
    });
    

    Note: I put the index in a variable so that I could easily test with different departments.

    Here is an example fiddle.