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

คุณสมบัติ HTML DOM Input URL maxLength

คุณสมบัติ maxLength ของ HTML DOM Input URL ใช้สำหรับดึงหรือกำหนดจำนวนตัวอักษรสูงสุดที่ป้อนได้ในช่อง URL ค่าเริ่มต้นคือ -1 (ไม่จำกัด)

ไวยากรณ์ (Syntax)

การดึงค่า maxLength

inputURLObject.maxLength

การกำหนดค่า maxLength

inputURLObject.maxLength = number

ตัวอย่างการใช้งาน

ตัวอย่างเปลี่ยน maxlength ของช่อง URL แล้วลองล็อกอิน

<!DOCTYPE html>
<html>
<head>
<title>Input URL maxLength</title>
<style>
  form {
    width: 70%;
    margin: 0 auto;
    text-align: center;
  }
  * {
    padding: 2px;
    margin: 5px;
  }
  input[type="button"] {
    border-radius: 10px;
  }
</style>
</head>
<body>
<form id="Google">
  <fieldset>
    <legend>URL-maxLength</legend>
    <label for="URLSelect">URL : <input type="url" id="URLSelect" maxLength="10"> </label> 
    <input type="button" onclick="logIN()" value="Log In"> 
    <input type="button" onclick="changeMaxLength()" value="Change Maxlength"> 
    <div id="divDisplay"></div> 
  </fieldset> 
</form> 
<script> 
  var divDisplay = document.getElementById("divDisplay"); 
  var inputURL = document.getElementById("URLSelect"); 
  divDisplay.textContent = 'Maxlength: ' + inputURL.maxLength; 
  function changeMaxLength() { 
    inputURL.maxLength += 10; 
    divDisplay.textContent = 'Maxlength: ' + inputURL.maxLength; 
  } 
  function logIN(){ 
    if(inputURL.value !== '') 
      divDisplay.textContent = 'Could not identify url, Redirecting to ' + inputURL.form.id; 
  } 
</script> 
</body>
</html>

ผลลัพธ์

เริ่มต้น - แสดง "Maxlength: 10" (พิมพ์ได้แค่ 10 ตัวอักษร)

คลิก "Change Maxlength" - แสดง "Maxlength: 20" (เพิ่มทีละ 10)

กรอก URL แล้วคลิก "Log In" - แสดง "Could not identify url, Redirecting to Google"

การใช้งาน: จำกัดความยาวข้อมูลที่รับได้ ป้องกันการโจมตี buffer overflow หรือข้อมูลยาวเกินไป