ใช้ event onkeypress ตรวจสอบ keyCode 13 (Enter)
ตัวอย่างโค้ด
<!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>
<input id="textBox" type="text" onkeypress="return demoForEnterKey(event)" />
<script>
function demoForEnterKey(eventName) {
if (eventName.keyCode == 13) {
var t = document.getElementById("textBox");
console.log(t.value);
console.log("Enter key is pressed.....");
return true;
} else {
console.log("Enter key is not pressed.....");
return false;
}
}
</script>
</body>
</html>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
พิมพ์ข้อความในช่อง Input แล้วกด Enter จะแสดงค่าและข้อความใน Console