Thuộc tính defaultValue của đối tượng Input Time trả về hoặc thiết lập giá trị mặc định ban đầu của ô nhập giờ. Khác với value (thay đổi khi người dùng nhập), defaultValue không đổi trừ khi gán lại qua JS. Dùng để reset form về trạng thái ban đầu.
Cú pháp
Lấy giá trị chuỗi
inputTimeObject.defaultValue
Thiết lập defaultValue
inputTimeObject.defaultValue = 'chuỗi'
Ví dụ minh họa
Form hẹn giờ: giá trị mặc định 09:30. Có nút đổi sang giờ thay thế, nút quay lại mặc định, nút xác nhận khóa form:
<!DOCTYPE html>
<html>
<head>
<title>Input Time defaultValue</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>
<fieldset>
<legend>Time-defaultValue</legend>
<label for="TimeSelect">Giờ hẹn: <input type="time" id="TimeSelect" value="09:30"> </label><br>
<input type="button" onclick="doiGio('Alternate')" value="Giờ thay thế">
<input type="button" onclick="doiGio('Default')" value="Giờ mặc định"><br>
<input type="button" onclick="xacNhanHen()" value="Xác nhận hẹn">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var inputTime = document.getElementById("TimeSelect");
function doiGio(str) {
if (inputTime.disabled === false) {
if(str === 'Alternate')
inputTime.value = '10:30';
else
inputTime.value = inputTime.defaultValue;
}
}
function xacNhanHen() {
inputTime.disabled = true;
divDisplay.textContent = 'Hẹn cố định lúc: ' + inputTime.value;
}
</script>
</body>
</html>
Kết quả
- Ban đầu: ô time 09:30.
- Nhấn Giờ thay thế: ô time thành 10:30.
- Nhấn Giờ mặc định: ô time quay về 09:30 (defaultValue).
- Nhấn Xác nhận hẹn: khóa ô, hiển thị giờ hiện tại.
Ứng dụng: Nút "Reset form" hoặc "Khôi phục mặc định" thường gán input.value = input.defaultValue cho tất cả input.