If if statement when array doesn't matter (Javascript + HTML)
I have an input field that stores various texts in an array and is displayed on another page, but I want the page to say "No events" when there is no value in the array
here is the javascript that adds the array to the page
function getEvents(){
//get the localstorage from the new event page
events = JSON.parse(localStorage.getItem("events"));
for (var i = 0; i < events.length; i++)
{
if (events === "undefined" || null || "") {
document.getElementById("none").innerHTML = "No events";
} else {
// title output
var title = document.createElement("h1"); //creates h1 element
var titleText = document.createTextNode(events[i].name); //assigns title
text
title.appendChild(titleText); //appends text to h1
document.getElementById("output").appendChild(title); //appends to the
page
// date output
var date = document.createElement("p"); //creates p element
var dateText = document.createTextNode(events[i].date); //assigns date
text
date.appendChild(dateText); //appends text to p
document.getElementById("output").appendChild(date); //appends to the page
}
}
}
And here is the html on the event loader page
<body onload="getEvents()">
<!-- Title -->
<center>
<h1>My Events</h1>
</center>
<p id="none"></p>
<div id="output">
</div>
</body>
+3
source to share
2 answers
You are iterating over the array so that you are testing the elements of the array, not the array itself. Your for loop won't even run if there is no array. Thus, it makes no sense in principle to run tests on the array itself within a loop.
You can continue this path just before going below the loop:
if (events.length == 0)
document.getElementById("none").innerHTML = "No events";
0
source to share