How to avoid inserting NULL values to a table with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

In order to get rid of null values inserted into a table, you need to check the condition while entering the value.

The condition to check NULL must be as follows −

while( !( yourVariableName1==null || yourVariableName2==null ||
yourVariableName3==null…...N){
   // yourStatement1
   .
   .
   N
}

The above logic will never allow inserting the null values.

Now you can use for loop and insert value into the table without NULL. Following is the code −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h2>Demo Of Inserting the value into the table</h2>
<p>This is demo on the javascript array</p>
<p id="demo"></p>
<script>
   var index = 0;
   var firstNameArray = new Array();
   var lastNameArray = new Array();
   var firstName = "";
   var lastName = "";
   while (!(firstName == null || lastName == null)) {
      firstName = prompt("Please Enter your First Name=");
      lastName = prompt("Please Enter your Last Name=");
      firstNameArray[index] = firstName;
      lastNameArray[index] = lastName;
      index++;
   }
   document.writeln("<table border='1' width='50%'>");
   document.writeln("<caption>DEMO TABLE IN JAVASCRIPT</caption>");
   document.writeln("<th>FirstName</th><th>LastName</th>");
   for (var startIndex in firstNameArray) {
      if (firstNameArray[startIndex] !== null &&
         lastNameArray[startIndex] !== null)
         document.writeln("<tr><td>" + firstNameArray[startIndex] +
         "</td><td>" + lastNameArray[startIndex] + "</td></tr>");
      }
      document.write("</table>");
</script>
</body>
</html>

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.

Output

This will produce the following output −

Now entering the first name.

This will produce the following output −

After clicking the OK button, you will get the following output −

Now, entering the last name This will produce the following output −

After clicking the OK button, now click the button Cancel two times, you will get the final output.

The final output table is as follows −

raja
Published on 14-Sep-2020 08:51:36
Advertisements