1 回答

TA貢獻2041條經驗 獲得超4個贊
let form = document.getElementById("form_Text").value;您正試圖在加載 js 后立即獲取輸入值。因此它永遠是空的。您需要在事件偵聽器中調用它。
document.getElementById("form_Text").onfocus = function() {
? ? let form = document.getElementById("form_Text").value;
? ? ...
}
input但是,您可以使用event 而不是focusand ,而不是編寫兩個單獨的事件偵聽器keyup
? ?
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.addEventListener('input', function(evt) {
? const inputValue = evt.target.value;
? if (inputValue == '') {
? ? formText.style.backgroundColor = "red";
? ? showText.innerHTML = "Form is empty";
? } else {
? ? formText.style.backgroundColor = "white";
? ? showText.innerHTML = "Form is not Empty, No red Background";
? }
})
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
更新
您可以在下面找到其他綁定方式。您可以使用事件偵聽器,而不是使用兩個單獨的事件(keyup和)。focusoninput
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.oninput = function(evt) {
? const inputValue = evt.target.value;
? if (inputValue == '') {
? ? formText.style.backgroundColor = "red";
? ? showText.innerHTML = "Form is empty";
? } else {
? ? formText.style.backgroundColor = "white";
? ? showText.innerHTML = "Form is not Empty, No red Background";
? }
}
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
添加回答
舉報