บทนำ
ใช้แอตทริบิวต์ maxlength กับ <textarea> เพื่อจำกัดจำนวนตัวอักษรสูงสุดที่กรอกได้
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<title>HTML Textarea Maxlength</title>
</head>
<body>
<form action="" method="get">
ต้องการปรับปรุงอะไรในวิทยาลัย? <br>
<textarea rows="5" cols="40" maxlength="100" name="description">
ใส่คำตอบที่นี่...
</textarea><br>
<input type="submit" value="submit" />
</form>
</body>
</html>
แอตทริบิวต์ Textarea สำคัญ (สรุป)
| แอตทริบิวต์ | ค่า | คำอธิบาย |
|---|---|---|
| maxlength | number | ตัวอักษรสูงสุด |
| minlength | number | ตัวอักษรต่ำสุด |
| rows | number | จำนวนบรรทัด |
| cols | number | ตัวอักษรต่อบรรทัด |
| wrap | hard/soft | การขึ้นบรรทัด |
| placeholder | text | ข้อความแนะนำ |
| required | required | บังคับกรอก |
| readonly | readonly | อ่านอย่างเดียว |
| disabled | disabled | ปิดการใช้งาน |
| autofocus | autofocus | โฟกัสอัตโนมัติ |
นับตัวอักษร Real-time (JavaScript)
<textarea id="txt" maxlength="200"></textarea>
<div>เหลือ <span id="count">200</span> ตัวอักษร</div>
<script>
document.getElementById('txt').addEventListener('input', function() {
document.getElementById('count').textContent = 200 - this.value.length;
});
</script>