Thuộc tính value của đối tượng Input Text trong HTML DOM trả về hoặc thiết lập giá trị chuỗi của thuộc tính value trong thẻ <input type="text">. Đây là thuộc tính cốt lõi để đọc/ghi dữ liệu người dùng nhập vào ô văn bản.
Cú pháp
Lấy giá trị chuỗi
inputTextObject.value
Thiết lập giá trị chuỗi
inputTextObject.value = 'Chuỗi_mới'
Ví dụ minh họa
Ví dụ dưới đây mô phỏng form đăng nhập đơn giản: nhập tên, điền tự động email, và xác thực khi nhấn nút Login.
<!DOCTYPE html>
<html>
<head>
<title>Input Text value</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>Text-value</legend>
<label for="TextSelect">Họ tên: <input type="text" id="TextSelect">
<input type="button" onclick="getUserText('david')" value="David">
<input type="button" onclick="getUserText('shasha')" value="Shasha"><br>
<input type="button" onclick="login()" value="Login">
</label>
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var inputText = document.getElementById("TextSelect");
function getUserText(userName) {
if(userName === 'david')
inputText.value = 'David Miller';
else
inputText.value = 'Shasha Green';
}
function login() {
if(inputText.value !== '')
divDisplay.textContent = 'Welcome ' + inputText.value.split("@")[0];
else
divDisplay.textContent = 'Enter Valid Text';
}
</script>
</body>
</html>
Kết quả
- Ban đầu: ô nhập trống, nhấn Login hiển thị "Enter Valid Text".
- Nhấn David hoặc Shasha: ô nhập được điền tự động.
- Nhấn Login sau khi đã điền: hiển thị lời chào欢迎.
Ứng dụng thực tế: Thuộc tính này thường dùng để: lấy dữ liệu form, điền sẵn giá trị mặc định, xóa form sau submit, hoặc validate đầu vào trước khi gửi server.