[英]JavaScript - Can you add a class to an Input element only if a certain condition is met?
I am having trouble with using JavaScript so that when a user tries to submit my HTML/CSS form while either of the input fields are blank, then the relevant field would appear 'highlighted' or outlined.我在使用 JavaScript 时遇到问题,因此当用户尝试提交我的 HTML/CSS 表单而任一输入字段为空白时,相关字段将显示为“突出显示”或概述。 My aim was to add a class (a transparent layer of some kind) to one of the input fields depending on if the field's value is blank or not.
我的目标是根据字段的值是否为空白,将 class(某种透明层)添加到其中一个输入字段。 I have so far tried using: element.classList.add("className");
到目前为止,我已经尝试过使用: element.classList.add("className"); with no luck.
没有运气。 The input fields are defined with no classes so I just wanted to add.
输入字段没有定义类,所以我只想添加。
Any help appreciated.任何帮助表示赞赏。
I would just loop over my inputs and check if their values are true or not, then change class name accordingly.我会遍历我的输入并检查它们的值是否为真,然后相应地更改 class 名称。 A input's value returns false if it's blank.
如果输入为空,则输入的值返回 false。
const form = document.querySelector("form");
const inputs = document.querySelectorAll("input");
form.addEventListener("submit", (event) => {
event.preventDefault();
checkInputs();
});
const checkInputs = () => {
inputs.forEach(input => {
if (input.value) {
input.className = "your-class-name-1"
} else {
input.className = "your-class-name-2"
}
})
};
As everyone told above, you should use the required parameter, but if you want to use your solution you should tell us what is not working.正如上面每个人所说,您应该使用所需的参数,但如果您想使用您的解决方案,您应该告诉我们什么不起作用。
I've checked your code and created a little form for this purpose like:我检查了您的代码并为此创建了一个小表单,例如:
<form id='form'>
<input type="text"/ id='form-field1' placeholder='1'>
<input type="text"/ id='form-field2' placeholder='2'>
<button type='submit'/>
</form>
Your code:你的代码:
const form = document.getElementById('form');
const a = document.getElementById('form-field1');
const b = document.getElementById('form-field2');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
const aValue = a.value.trim();
const bValue = b.value.trim();
console.log(aValue);
console.log(bValue);
if (aValue === "") {
a.classList.add("red-transparent-overlay");
} else {
a.classList.add("green-transparent-overlay");
}
}
and submitting my form when the first field is null adds red-transparent-overlay class to the first field, the same happens with the second statement, so your code is working.并在第一个字段为 null 时提交我的表单,将 red-transparent-overlay class 添加到第一个字段,第二个语句也是如此,因此您的代码正在运行。
Make sure you remove the other class when you add a class.添加 class 时,请确保删除其他 class。
if (aValue === "") {
a.classList.add("red-transparent-overlay");
a.classList.remove("green-transparent-overlay");
} else {
a.classList.add("green-transparent-overlay");
a.classList.remove("red-transparent-overlay");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.