【问题标题】:Required field in form doesn´t change to red after erasing input content删除输入内容后,表单中的必填字段不会变为红色
【发布时间】:2021-01-31 16:05:20
【问题描述】:

基本表单验证

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

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

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

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

当用户释放按键(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>

【问题讨论】:

    标签: javascript onkeyup onfocus


    【解决方案1】:

    您正在尝试在加载 js 后立即使用 let form = document.getElementById("form_Text").value; 获取输入值。因此它将永远是空的。您需要在事件侦听器中调用它。

    document.getElementById("form_Text").onfocus = function() {
        let form = document.getElementById("form_Text").value;
        ...
    }
    

    但您可以使用input 事件代替focuskeyup,而不是编写两个单独的事件侦听器

       
    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>

    更新

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

    这是一个比较 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>

    【讨论】:

    • 嗨,Harun,您的编辑更有意义,感谢您解决这个问题..!由于我还没有了解 addEventListener 我不了解那部分,请您用“onfocus”和“onkeyup”解决挑战
    • 抱歉回复晚了。我最近真的很忙。我按照您的要求更新了答案。请看一下。
    • 非常感谢 Harun 帮了大忙,我很感激..!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2017-10-12
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多