ใช้ isNaN() ตรวจสอบว่าเป็น NaN (Not a Number) หรือไม่
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="checkingInput" action="" onsubmit="return checkInputIsNumber()">
Enter the value: <input type="text" name="txtValue">
<br>
<input type="submit" value="check">
</form>
<script>
function checkInputIsNumber() {
var value = document.forms["checkingInput"]["txtValue"].value;
if (isNaN(value)) {
alert("Please Provide the input as a number");
return false;
}
}
</script>
</body>
</html>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
กรอกตัวอักษรแล้วกด Submit จะ Alert แจ้งเตือน ต้องกรอกตัวเลขเท่านั้น