คุณสมบัติ maxLength ของ HTML DOM Textarea ใช้สำหรับคืนค่าและแก้ไขค่าของแอตทริบิวต์ maxlength ขององค์ประกอบ textarea ในเอกสาร HTML
ไวยากรณ์
1. การคืนค่า maxLength
object.maxLength
2. การแก้ไข maxLength
object.maxLength = "number"
ตัวอย่าง
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 40%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
}
.show {
font-size: 1.5rem;
margin: 1rem 0;
}
</style>
<body>
<h1>ตัวอย่างคุณสมบัติ Textarea maxLength ของ DOM</h1>
<textarea maxlength="50">สวัสดี! ฉันคือองค์ประกอบ textarea พร้อมข้อความตัวอย่าง</textarea>
<button onclick="set()" class="btn">แสดงความยาวสูงสุด</button>
<div class="show"></div>
<script>
function set() {
document.querySelector('.show').innerHTML = 'จำนวนตัวอักษรสูงสุดที่อนุญาตใน textarea ด้านบนคือ ' + document.querySelector("textarea").maxLength;
}
</script>
</body>
</html>
ผลลัพธ์
คลิกปุ่ม "แสดงความยาวสูงสุด" เพื่อแสดงค่าของแอตทริบิวต์ maxlength ขององค์ประกอบ textarea