Thuộc tính maxLength của đối tượng Input URL trong HTML DOM trả về hoặc thiết lập số ký tự tối đa cho phép nhập vào ô URL. Giá trị mặc định -1 (không giới hạn).
Cú pháp
Lấy maxLength
inputURLObject.maxLength
Thiết lập maxLength
inputURLObject.maxLength = số_nguyên
Ví dụ minh họa
Ô URL maxLength=10. Nhấn nút tăng 10, nút login kiểm tra form.id:
<!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="dangNhap()" value="Đăng nhập">
<input type="button" onclick="tangMaxLength()" value="Tăng Maxlength">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var inputURL = document.getElementById("URLSelect");
divDisplay.textContent = 'Maxlength: ' + inputURL.maxLength;
function tangMaxLength() {
inputURL.maxLength += 10;
divDisplay.textContent = 'Maxlength: ' + inputURL.maxLength;
}
function dangNhap(){
if(inputURL.value !== '')
divDisplay.textContent = 'Không nhận diện URL, chuyển đến ' + inputURL.form.id;
}
</script>
</body>
</html>
Kết quả
- Ban đầu: "Maxlength: 10", ô chỉ nhập được 10 ký tự.
- Nhấn Tăng Maxlength: "Maxlength: 20", ô cho nhập 20 ký tự.
- Nhập URL, nhấn Đăng nhập: "Không nhận diện URL, chuyển đến Google".
Lưu ý: maxLength tính theo ký tự UTF-16 code unit. Ký tự Unicode đặc biệt (emoji, chữ Hán) có thể tính là 2 đơn vị.