[英]JavaScript Change the text fields when the user fills or not when the text field loses focus
我需要一项作业的帮助:当用户填写文本字段并且文本字段失去焦点时,用复选标记将文本字段设为绿色。 您可以使用 FontAwesome 中的复选标记。 当用户未填写文本字段但移除焦点时,将文本字段设为红色并带有叉号 我需要 javascript/dom 代码来完成此任务。 我试过这段代码但不起作用:
let fields = document.getElementsByTagName("input");
const checkFields = function () {
for (let i = 0; i < fields.length; i++) {
if (fields[i].value == "") {
fields[i].style.backgroundColor = "red";
} else {
fields[i].style.backgroundColor = "green";
}
}
}
fields.addEventListener('change', checkFields)
<div class="controls">
<input
autofocus=""
class="input-xlarge"
id="company"
name="company"
placeholder="Company name"
type="text"
value=""
/>
</div>
</section>
<section class="control-group">
<label class="control-label" for="fname">Name</label>
<div class="controls two-col">
<input
class="input-medium"
id="fname"
name="fname"
placeholder="First name"
type="text"
value=""
/>
</div>
<div class="controls two-col">
<input
class="input-medium"
id="lname"
name="lname"
placeholder="Last name"
type="text"
value=""
/>
</div>
</section>
<section class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input
class="input-xlarge"
id="email"
name="email"
placeholder="Email"
type="email"
value=""
/>
</div>
</section>
这是您的解决方案:
// Select Each Input document.querySelectorAll('input').forEach((inp) => { // Remove whitespace from value and check it // Add eventlistener on each input inp.addEventListener('change', () => { let value = inp.value.split(' ').join('') // Do something with value; if (value == "") { inp.style.backgroundColor = "red"; } else { inp.style.backgroundColor = "green"; } }) })
<section> <div class="controls"> <input autofocus="" class="input-xlarge" id="company" name="company" placeholder="Company name" type="text" value="" /> </div> </section> <section class="control-group"> <label class="control-label" for="fname">Name</label> <div class="controls two-col"> <input class="input-medium" id="fname" name="fname" placeholder="First name" type="text" value="" /> </div> <div class="controls two-col"> <input class="input-medium" id="lname" name="lname" placeholder="Last name" type="text" value="" /> </div> </section> <section class="control-group"> <label class="control-label" for="email">Email</label> <div class="controls"> <input class="input-xlarge" id="email" name="email" placeholder="Email" type="email" value="" /> </div> </section>
您可以使用“focusout”事件,如果我正确理解您的问题,我相信这将是更好的选择。
const ips = document.querySelectorAll("input")
ips.forEach(ip=>ip.addEventListener("focusout", ()=>{
const text = ip.value
if (text === "") ip.style.border= "1px solid red"
else ip.style.border = "1px solid green"
})
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.