ใช้แอตทริบิวต์ name เพื่อตั้งชื่อองค์ประกอบ ใช้ได้กับองค์ประกอบ HTML ต่อไปนี้: <button>, <fieldset>, <form>, <iframe>, <input>, <map>, <meta>, <object>, <output>, <param>, <select>, <textarea>
ตัวอย่าง
ลองรันโค้ดต่อไปนี้เพื่อใช้งานแอตทริบิวต์ name:
<!DOCTYPE html>
<html>
<body>
Subject: <input type="text" name="sub" spellcheck="true">
<p>Add an incorrect spelling for a word above and see what happens.</p>
<p contenteditable="true" spellcheck="true">This is an editable conttent, with a spelling mistake. Click to edit.</p>
</body>
</html>
บทบาทของ name ในแต่ละองค์ประกอบ
| องค์ประกอบ | หน้าที่ของ name |
|---|---|
<input>, <textarea>, <select> |
Key สำหรับส่งข้อมูลฟอร์ม (key ใน FormData) |
<form> |
Identifier สำหรับ document.forms.name และ form attribute |
<button>, <input type="submit"> |
ส่งค่า name=value เมื่อคลิก submit (หลายปุ่ม submit) |
<iframe> |
Target name สำหรับ target ของ form/link, window.frames.name |
<map> |
ชื่อ Image Map ใช้กับ usemap="#name" ของ img |
<meta> |
Metadata name (เช่น name="description", "viewport") |
<object>, <param>, <output> |
Identifier สำหรับ scripting และ form submission |
ตัวอย่าง: หลายปุ่ม Submit
<form action="/process" method="post">
<input type="text" name="username" placeholder="Username">
<button type="submit" name="action" value="save">Save</button>
<button type="submit" name="action" value="publish">Publish</button>
<button type="submit" name="action" value="preview">Preview</button>
</form>
<!-- Server receives: action=save หรือ action=publish หรือ action=preview -->
Radio Buttons - name เดียวกัน = กลุ่มเดียว
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
<label><input type="radio" name="gender" value="other"> Other</label>
</fieldset>
ความแตกต่าง: name vs id
| คุณสมบัติ | name |
id |
|---|---|---|
| วัตถุประสงค์ | Form submission, grouping | Unique identifier, CSS/JS selector, anchor |
| ความเป็นเอกลักษณ์ | ซ้ำได้ (radio, checkbox group) | ต้อง Unique ทั้งหน้า |
| เข้าถึงด้วย JS | form.elements.name |
document.getElementById() |