บทนำ
ใช้แอตทริบิวต์ maxlength กับ <input type="text"> เพื่อจำกัดจำนวนตัวอักษรสูงสุด
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<title>HTML Maxlength Attribute</title>
</head>
<body>
<form action="/cgi-bin/hello_get.cgi" method="get">
ชื่อนักเรียน: <br>
<input type="text" name="first_name" maxlength="40" /><br>
วิชา: <br>
<input type="text" name="last_name" maxlength="30" /><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
แอตทริบิวต์เกี่ยวกับความยาว
| แอตทริบิวต์ | ใช้กับ | คำอธิบาย |
|---|---|---|
maxlength | text, textarea, search, url, tel, email, password | ตัวอักษรสูงสุด |
minlength | text, textarea, search, url, tel, email, password | ตัวอักษรต่ำสุด (HTML5) |
size | text, search, url, tel, email, password | ความกว้างมองเห็น (ตัวอักษร) |
นับตัวอักษร Real-time
<input type="text" maxlength="50" id="username">
<span id="charCount">0</span>/50
<script>
document.getElementById('username').addEventListener('input', function() {
document.getElementById('charCount').textContent = this.value.length;
});
</script>