亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

擦除輸入內容后,表單中的必填字段不會變為紅色

擦除輸入內容后,表單中的必填字段不會變為紅色

慕少森 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 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號