簡體   English   中英

JavaScript - 僅當滿足特定條件時,您能否將 class 添加到輸入元素?

[英]JavaScript - Can you add a class to an Input element only if a certain condition is met?

我在使用 JavaScript 時遇到問題,因此當用戶嘗試提交我的 HTML/CSS 表單而任一輸入字段為空白時,相關字段將顯示為“突出顯示”或概述。 我的目標是根據字段的值是否為空白,將 class(某種透明層)添加到其中一個輸入字段。 到目前為止,我已經嘗試過使用: element.classList.add("className"); 沒有運氣。 輸入字段沒有定義類,所以我只想添加。

任何幫助表示贊賞。

我會遍歷我的輸入並檢查它們的值是否為真,然后相應地更改 class 名稱。 如果輸入為空,則輸入的值返回 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"
        }
    })

};

正如上面每個人所說,您應該使用所需的參數,但如果您想使用您的解決方案,您應該告訴我們什么不起作用。

我檢查了您的代碼並為此創建了一個小表單,例如:

<form id='form'>
<input type="text"/ id='form-field1' placeholder='1'>
<input type="text"/ id='form-field2' placeholder='2'>
<button type='submit'/>
</form>

你的代碼:

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");
    }
}

並在第一個字段為 null 時提交我的表單,將 red-transparent-overlay 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM