Even though the if statement has been implemented, the page continues to show null objects

So, I have an if statement that filters out null objects and it's working fine. However, when I try to insert something in join() like join("li"), all null objects are displayed on the page as shown in the image. I just want to display objects that are not null, but when I tried another join("\n"), it didn't work as expected.
https://i.sstatic.net/12PuM.png

var vitalTest = document.getElementById("vitalComments").value
              = systemList[0].comments.join("");

//alert(vitalTest);

if (vitalTest == ""){
}else{
    document.getElementById("vitalComments").innerHTML = systemList[0].comments.join("<li>");
    var vitalTitleq = document.getElementById("vitalTitle").innerHTML
                    = systemList[0].systemName;
}

Answer №1

Your if statement will only evaluate to true when all elements in the array are empty. If only some elements are not empty, the code will proceed to the else statement where empty values are still used.

Instead, consider using Array#filter or a polyfill to remove empty values and work with the new filtered array.

valuelist = systemList[0].comments.filter(comment=>comment);

The function comment=>comment is an arrow function that simply returns the item, which will then be tested as truthy or falsy. Since null, undefined, and empty strings evaluate to falsy, they will be filtered out. If you need to retain values like 0 or other falsy types, you will need a different function.

Demo

var list = [1,null,"text",null,44];

var filtered = list.filter(item=>item);

document.querySelector('ul').innerHTML = "<li>"+filtered.join('</li><li>')+"</li>";
<ul></ul>

Answer №2

Consider implementing the function provided below.

function displayComments(objID, comments) {
  if(Array.isArray(comments) && comments.length>0) {
  var filteredComments = comments.map(function(comment) {
      comment = comment.replace(/(\r\n|\n|\r|\s)/gm,"");
      if(comment.length>0) {
          return '<li>'+comment+'</li>';
      }
  });
  document.getElementById(objID).innerHTML = filteredComments.join("");
  }
}

function displayComments(comments) {
  if(Array.isArray(comments) && comments.length>0) {
  var filteredComments = comments.map(function(comment) {
      comment = comment.replace(/(\r\n|\n|\r|\s)/gm,"");
      if(comment.length>0) {
          return '<li>'+comment+'</li>';
      }
  });
  document.getElementById("vitalComments").innerHTML = filteredComments.join("");
  }
}
var comments = ["comment1"," ","","comment2\n","comment3"];

displayComments(comments);
<ul id="vitalComments"></ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Implementing class toggling in AngularJS with ng-class

Trying to change the class of an element with ng-class <button class="btn"> <i ng-class="{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}"></i> </button> isAutoScroll(): $scope.isAutoScrol ...

Identify data points on the line chart that fall outside the specified range with ng2-charts

I'm struggling to figure out how to highlight specific points on a line chart that fall outside a certain range. For instance, if the blood sugar level is below 120, I want to display that point as an orange dot. If it's above 180, I want to show ...

Is there an issue with retrieving data from asp.cs through ajax?

Currently, I am in the process of learning asp.net and trying to access server data to populate a textbox with the retrieved information. public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) ...

Top Choice for Customizable Location Bar Dragging

I'm currently working on an app that features a draggable location bar. This feature will allow users to navigate through chapters in a book and will be displayed at the bottom of the screen, similar to Kindle or other mobile reading applications. I ...

Using PHP variables in JavaScript is not compatible

Currently, I am facing an issue where PHP variables inside the javascript code are not being echoed. When I try to echo the variables outside of the javascript, everything works perfectly fine. After carefully reviewing my code multiple times, I still cann ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

What could be the reason for the absence of Mock Service Worker in a React project that has Typescript enabled?

After attempting to integrate Mock Service Worker into my React project with Typescript support, I encountered errors when running the npm install msw --save-dev command. The terminal displayed the following messages: PS F:\Programming\React Prac ...

Unable to maintain active status on Vuejs (PrimeVue) Sidebar component leads to malfunction

I currently have a PrimeVue Sidebar component set up with a dynamic component being passed to it. At the moment, I am only using a single component to test this functionality. <Sidebar v-model:visible="sidebarState" :baseZIndex="1000" ...

Stop Rails application from inadvertently responding to AJAX requests made by jQuery

Having developed a rather intricate Rails (2.3.8) application with plenty of jQuery ajax requests, I find myself facing an intermittent bug that is quite challenging to reproduce. Occasionally, a jQuery $.ajax({..}) request will attempt to access a page it ...

What is the process to change the URL?

Currently, I am deep into developing a large-scale web application for a company. The project has been ongoing for about four months now, and we have encountered a harmless yet annoying issue that we haven't had time to address. The problem lies in t ...

Apply the `text-overflow: ellipsis` property to truncate the text of two items within a flex column, which is contained within

I am attempting to accomplish the following: https://i.sstatic.net/H0pB0.jpg Successfully implementing ellipsis for a single item is achieved with: white-space: nowrap; overflow: hidden; text-overflow: ellipsis; However, my challenge lies in truncating ...

What is the best way to show the interior color of a cube in three.js?

My plan is to create a room using THREE.js starting from a basic cube. Here's what I have written so far: function loadModelcube() { console.log("Function executed successfully"); cube.traverse( function( node ) { if( node.material ) { ...

Width and left values don't play well with absolute positioning

I am encountering an issue where a div with absolute positioning, which is a child of another absolute positioned element, is not behaving as expected. Despite setting width:100%; left:1px; right:1px on the child element, it extends beyond its parent. < ...

Place a pair of divs in the center next to one another

What is the best way to align two divs in the center beside each other with some padding in between that actually works? I attempted using display: inline, but it didn't have the desired effect. .my-container { position: rela ...

Tracking the advancement of synchronous XMLHttpRequest requests

Within the client-side environment, there exists a File-Dropzone utilizing the HTML5 File-API which allows users to drop multiple files for uploading to the server. Each file triggers the creation of a new XMLHttpRequest Object that asynchronously transfer ...

Expanding Lists in Bootstrap 3: A Step-by-Step Guide

I have been experimenting with Bootstrap's Example accordion code, which can be accessed via this link: http://jsfiddle.net/qba2xgh6/18/ <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel ...

When scrolling, the fixed menu bar at the top of the page is making the content below jump

I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows: $(window).scroll(function () { if ($(window).scrollTop() > 175) { $('#loca ...

What steps can be taken to ensure your bot successfully sends the second argument?

Who just handed out an L to user#0000? Looks like JohnGameRage#0000 did! ...

The shading of the box isn't displaying the correct color in Microsoft Edge and IE 11

I have a unique pattern consisting mainly of white and grey hues. To add a touch of color, I am using the box shadow property in CSS to apply a blue filter effect. This technique successfully displays the desired result in Firefox and Chrome browsers. Howe ...