DeadlyDragonnn
DeadlyDragonnn

Reputation: 7

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. 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. I have so far tried using: element.classList.add("className"); with no luck. The input fields are defined with no classes so I just wanted to add.

Any help appreciated.

Upvotes: 0

Views: 1439

Answers (3)

General Butt Naked
General Butt Naked

Reputation: 31

I would just loop over my inputs and check if their values are true or not, then change class name accordingly. A input's value returns false if it's blank.

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

};

Upvotes: 1

Barmar
Barmar

Reputation: 781726

Make sure you remove the other class when you add a 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");
    }

Upvotes: 0

browinski
browinski

Reputation: 21

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.

Upvotes: 0

Related Questions