0

基本表单验证

在这个问题中,您将确保文本框不为空。完成以下步骤:

创建一个文本输入框。编写一个函数,如果文本框为空,则将文本框的边框变为红色。

(如果值等于“”,则为空)。

如果值不为空,边框应该恢复正常。

当用户释放一个键(onkeyup)时,运行你刚刚创建的函数。

请在我编码错误的地方更正我的代码?

let form = document.getElementById("form_Text").value;
document.getElementById("form_Text").onfocus = function() {
  if (form == "") {
    document.getElementById("form_Text").style.backgroundColor = "red";
    document.getElementById("showText").innerHTML = "Form is empty";
  } else {}
  document.getElementById("form_Text").onkeyup = function() {
    document.getElementById("form_Text").style.backgroundColor = "white";
    document.getElementById("showText").innerHTML =
      "Form is not Empty, No red Background";
  };
};
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>

4

1 回答 1

2

您正在尝试在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>


更新

您可以在下面找到另一种绑定方式。您可以使用事件侦听器,而不是使用两个单独的事件(keyupfocus) 。oninput

这是一个比较keyupinput事件的 SO 线程:https ://stackoverflow.com/a/38502715/1331040

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>

于 2020-10-17T09:39:33.590 回答