为了账号安全,请及时绑定邮箱和手机立即绑定

擦除输入内容后,表单中的必填字段不会变为红色

擦除输入内容后,表单中的必填字段不会变为红色

慕少森 2023-05-19 14:44:38
基本表单验证在这个问题中,您要确保文本框不为空。完成以下步骤:创建一个文本输入框。编写一个函数,如果文本框为空,则将文本框的边框变为红色。(如果值为“”,则为空)。如果值不为空,边框应该恢复正常。当用户释放一个键 (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>
查看完整描述

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>


查看完整回答
反对 回复 2023-05-19
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信