Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วัตถุ Textarea ใน HTML DOM: คุณสมบัติและเมธอดครบวงจร

วัตถุ Textarea (HTMLTextAreaElement) คืออะไร?

วัตถุ Textarea ใน HTML DOM แทนเอลิเมนต์ <textarea> ใช้สำหรับ **รับข้อความหลายบรรทัด** จากผู้ใช้ มีคุณสมบัติและเมธอดเฉพาะสำหรับจัดการข้อความ, สถานะ, และรูปแบบ

การสร้าง Textarea ด้วย JavaScript

var textarea = document.createElement('TEXTAREA'); // หรือ 'textarea'
textarea.rows = 5;
textarea.cols = 30;
textarea.placeholder = 'พิมพ์ข้อความที่นี่...';
document.body.appendChild(textarea);

คุณสมบัติ (Properties) สำคัญ

คุณสมบัติ คำอธิบาย ประเภท
valueเนื้อหาปัจจุบันของ textarea (อ่าน/เขียนได้) - **ใช้บ่อยที่สุด**String
defaultValueค่าเริ่มต้นจาก HTML attribute (สำหรับ reset form)String
placeholderข้อความแนะนำ (Placeholder text)String
rowsจำนวนแถวที่แสดง (ความสูง)Integer
colsจำนวนคอลัมน์ที่แสดง (ความกว้าง)Integer
maxLengthจำนวนตัวอักษรสูงสุดที่อนุญาต (0 = ไม่จำกัด)Integer
readOnlytrue/false: อ่านอย่างเดียว (แตกต่างจาก disabled)Boolean
disabledtrue/false: ปิดใช้งาน ไม่ส่งค่ากับฟอร์มBoolean
requiredtrue/false: บังคับกรอก (HTML5 Validation)Boolean
nameชื่อฟิลด์ (สำหรับส่งฟอร์ม)String
formอ้างอิงไปยัง <form> ที่ครอบคลุม (Read-only)HTMLFormElement
autofocustrue/false: โฟกัสอัตโนมัติเมื่อโหลดหน้าBoolean
wrapโหมดการขึ้นบรรทัด: soft (ค่าเริ่มต้น), hard, offString
typeคืนค่า "textarea" เสมอ (Read-only)String
selectionStartตำแหน่งเริ่มต้นของการเลือกข้อความ (Cursor position)Integer
selectionEndตำแหน่งสิ้นสุดของการเลือกข้อความInteger
selectionDirectionทิศทางการเลือก: forward, backward, noneString

เมธอด (Methods) สำคัญ

เมธอด คำอธิบาย
select()เลือกข้อความทั้งหมดใน textarea
setRangeText(replacement, start, end, selectMode)แทนที่ข้อความในช่วงที่ระบุ (HTML5)
setSelectionRange(start, end, direction)ตั้งค่าช่วงการเลือก (Cursor/Selection)
checkValidity()ตรวจสอบความถูกต้องตาม constraints (required, maxlength ฯลฯ)
reportValidity()ตรวจสอบและแสดงข้อความผิดพลาดของเบราว์เซอร์

ตัวอย่าง: สร้าง Textarea และอ่านค่า

<!DOCTYPE html>
<html>
<style>
  body { color: #000; background: lightseagreen; height: 100vh; text-align: center; }
  .btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
  textarea { width: 80%; max-width: 500px; margin: 1rem auto; display: block; }


การจัดการ Selection และ Cursor

// อ่านตำแหน่งเคอร์เซอร์
var start = textarea.selectionStart;
var end = textarea.selectionEnd;

// ตั้งค่าเคอร์เซอร์ (วางที่ตำแหน่ง 10)
textarea.setSelectionRange(10, 10);
textarea.focus();

// เลือกข้อความช่วงที่ 5-15
textarea.setSelectionRange(5, 15);

// แทนที่ข้อความที่เลือก
textarea.setRangeText('ข้อความใหม่', start, end, 'select'); // 'select' = เลือกข้อความใหม่

เหตุการณ์ (Events) ที่เกี่ยวข้อง

  • input: ทุกครั้งที่ค่าเปลี่ยน (พิมพ์, ลบ, วาง) - **แนะนำใช้แทน keypress
  • change: เมื่อเสร็จสิ้นการแก้ไขและ blur (ออกจากฟิลด์)
  • select: เมื่อผู้ใช้เลือกข้อความ
  • keydown, keyup: การกดแป้นพิมพ์