Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ป้องกันการ Insert NULL Values ลง Table ด้วย JavaScript

วิธีทำ

ตรวจสอบเงื่อนไขก่อน insert โดยใช้ while loop ตรวจสอบ null

เงื่อนไขตรวจสอบ NULL

while(!(yourVariableName1==null || yourVariableName2==null || yourVariableName3==null...)){ 
  // your statements 
}

ตัวอย่างโค้ด

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=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>

วิธีรัน

บันทึกไฟล์ .html คลิกขวาเลือก "Open with Live Server" ใน VS Code

ผลลัพธ์

ป้องกันการ Insert NULL Values ลง Table ด้วย JavaScript

กรอก First Name:

ป้องกันการ Insert NULL Values ลง Table ด้วย JavaScript

กรอก Last Name:

ป้องกันการ Insert NULL Values ลง Table ด้วย JavaScript

กด Cancel 2 ครั้ง ได้ตารางสุดท้าย:

ป้องกันการ Insert NULL Values ลง Table ด้วย JavaScript

คำอธิบาย

prompt() คืนค่า null เมื่อกด Cancel
while(!(firstName == null || lastName == null)) วนลูปจนกว่าจะกด Cancel
ก่อน insert ตรวจสอบ !== null อีกครั้ง ป้องกัน null เข้า table