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

วิธาจำกัดจำนวนตัวอักษรในช่องกรอกข้อความฟอร์ม


บทนำ

ใช้แอตทริบิวต์ 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>

แอตทริบิวต์เกี่ยวกับความยาว

แอตทริบิวต์ใช้กับคำอธิบาย
maxlengthtext, textarea, search, url, tel, email, passwordตัวอักษรสูงสุด
minlengthtext, textarea, search, url, tel, email, passwordตัวอักษรต่ำสุด (HTML5)
sizetext, 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>