อ่านค่า value จาก input element ด้วย .value property
ใช้ document.getElementById() หา element แล้วอ่าน .value
ตัวอย่างโค้ดเต็ม
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Form Value</title>
</head>
<body>
<input type="text" id="getValues" value="My Name is John Smith" />
<script>
var originalValue = document.getElementById("getValues").value;
console.log("ค่าในช่องกรอก = " + originalValue);
</script>
</body>
</html>
วิธีรัน
บันทึกเป็น index.html แล้วเปิดด้วย Live Server ดู Console (F12)
คำอธิบาย
document.getElementById("id")ค้นหา element โดย ID.valueproperty ดึง/ตั้งค่า value ของ input, textarea, select- ทำงานได้กับ
<input>, <textarea>, <select>
การประยุกต์: ดึงค่าฟอร์มทั้งหมด
const form = document.getElementById('myForm');
const formData = new FormData(form);
const data = Object.fromEntries(formData);
console.log(data); // { field1: "value1", field2: "value2", ... }