[英]Javascript change input field color
我有這個代碼(工作正常)可以改變所有字段的顏色,無論該字段是否為空:
document.querySelectorAll("input").forEach((inp) => {
inp.addEventListener("focusout", () => {
let value = inp.value.split(" ").join("");
if (value == "") inp.style.backgroundColor = 'red';
else inp.style.backgroundColor = 'green';
});
});
現在我想驗證名字字段,它應該只能輸入字母。 如果是錯誤的,我希望它顯示為紅色。 我嘗試使用以下代碼,但它不起作用。 有任何想法嗎?
let firstName = document.querySelector("#fname");
firstName.addEventListener("focusout", () => {
if (typeof firstName.value != "string") {
firstName.value.style.backgroundColor = "red";
console.log(firstName.value);
} else {
firstName.value.style.backgroundColor = "green";
}
});
您可以使用正則表達式來檢查字符串是否有數字。 就像是:
let firstName = document.querySelector("#fname");
firstName.addEventListener("focusout", () => {
let hasNumber = /\d/;
if (hasNumber.test(firstName.value)) {
firstName.value.style.backgroundColor = "red";
console.log(firstName.value);
} else {
firstName.value.style.backgroundColor = "green";
}
});
value
將始終是一個字符串,因此您應該測試該字符串包含哪些字符,並且您可以使用正則表達式來測試它是否只包含字母表中的字母。
let firstName = document.querySelector("#fname"); firstName.addEventListener("focusout", () => { if (!/[a-zA-Z]+/.test(firstName.value)) { firstName.style.backgroundColor = "#FF374E"; } else { firstName.style.backgroundColor = "#c0eb34"; } });
<input id="fname" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.