แอตทริบิวต์ value คืออะไร?
แอตทริบิวต์ value ของเอลิเมนต์ <input> ใช้สำหรับ กำหนดค่าเริ่มต้น หรือ อ่านค่าปัจจุบัน ที่ผู้ใช้กรอก/เลือก คุณสมบัติ .value ใน JavaScript (DOM Property) ใช้เข้าถึงและแก้ไขค่านี้ได้
การใช้งานกับประเภท input ต่างๆ
| ประเภท Input |
การทำงานของ value |
| text, email, url, tel, password, search, number, date, time, datetime-local, month, week | ข้อความที่ผู้ใช้พิมพ์/เลือก (อ่าน/เขียนได้) |
| checkbox, radio | ค่าที่จะส่งเมื่อถูกเลือก (ค่าเริ่มต้นคือ "on") - ต้องตั้งค่า value="something" เอง |
| hidden | ค่าที่ส่งไปกับฟอร์ม แต่ไม่แสดงให้ผู้ใช้เห็น |
| file | **อ่านอย่างเดียว** (Read-only) ไม่สามารถตั้งค่าได้ทาง JavaScript เพื่อความปลอดภัย |
| button, submit, reset, image | ข้อความที่แสดงบนปุ่ม (Button label) |
| color | ค่าสีในรูปแบบ Hex (#rrggbb) |
| range | ค่าตัวเลขในช่วงที่กำหนด |
ตัวอย่าง: การตั้งค่าและอ่านค่า URL Input
<!DOCTYPE html>
<html>
<head>
<title>Input URL value Demo</title>
<style>
form { width: 70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin: 5px; }
input[type="button"] { border-radius: 10px; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>ตัวอย่าง URL Input</legend>
<label for="urlInput">เว็บไซต์:
<input type="url" id="urlInput" placeholder="https://example.com">
<input type="button" onclick="setUrl('google')" value="Google">
<input type="button" onclick="setUrl('github')" value="GitHub"><br>
<input type="button" onclick="goToUrl()" value="ไปยังเว็บไซต์">
</label>
<div id="output"></div>
</fieldset>
</form>
<script>
var output = document.getElementById("output");
var urlInput = document.getElementById("urlInput");
function setUrl(site) {
if (site === 'google') urlInput.value = 'https://www.google.com';
else if (site === 'github') urlInput.value = 'https://github.com';
}
function goToUrl() {
var url = urlInput.value.trim();
if (url) {
output.textContent = 'กำลังเปิด: ' + url;
// window.open(url, '_blank'); // ยกเลิกความคิดเห็นเพื่อเปิดจริง
} else {
output.textContent = 'กรุณาเลือกหรือป้อน URL';
}
}
</script>
</body>
</html>
ความแตกต่างระหว่าง Attribute และ Property
| แอตทริบิวต์ (HTML Attribute) |
โพรเพอร์ตี้ (DOM Property) |
getAttribute('value') / setAttribute('value', ...) | element.value (แนะนำให้ใช้ตัวนี้) |
| ค่าเริ่มต้นใน HTML (Initial value) | ค่าปัจจุบัน (Current value) - เปลี่ยนได้ตลอดเวลา |
| ไม่เปลี่ยนเมื่อผู้ใช้พิมพ์ | อัปเดตทันทีเมื่อผู้ใช้พิมพ์/เลือก |
ใช้สำหรับ Reset Form (<input type="reset">) | ใช้สำหรับอ่าน/เขียนค่าปัจจุบันทาง JS |
คำแนะนำ
- ใช้
element.value สำหรับอ่าน/เขียนค่าปัจจุบันใน JavaScript
- ใช้
element.defaultValue หากต้องการอ่านค่าเริ่มต้นจาก HTML
- สำหรับ
<input type="file"> ใช้ element.files แทน (FileList object)
- การตั้งค่า
value บน checkbox/radio ไม่ทำให้เกิดการเลือก (Checked) ต้องใช้ element.checked = true