Rodrigo Liva
Rodrigo Liva

Reputation: 67

Add a class to a form input

I'm having a problem with adding a class to a form input (I'm trying to make a form validator that the border would turn red if it was empty) I can add the error class in several types of tags except the input, why does this happen? (I used class because I plan to put more forms and I was stuck right at the beginning of development)

CSS

button {
    height: 50px;
    width: 200px;
    font-size: 28px;
    margin: 100px 0px;
}

.error {
    border: 2px solid red;
} 

.form-control {
    border-radius: 2px;
    font-size: 32px;
    width: 300px;
    height: 50px;
}

HTML

    <div>
        <form>
            <input type="text" name="digitar" id="digitar" class='form-control'><br>
            <button id='myBtn'>Clique aqui!</button>
        </form>
    </div>

Javascript

let element = document.getElementsByClassName('form-control')

document.getElementById("myBtn").addEventListener("click", function(){
    event.preventDefault()
    element.classList.add("error");
})

Upvotes: 0

Views: 1362

Answers (3)

yanmarex
yanmarex

Reputation: 11

You could use css to make it.

First add the atribute required in your input tag.

<input type="text" name="digitar" id="digitar" class='form-control' required>

Then in your css.

.form-control:focus:invalid {
    border: 2px solid red;
}

It will focus the forms that are invalid (empty).

Upvotes: 1

Manikanta Chinta
Manikanta Chinta

Reputation: 151

If you are trying to get elements by document.getElementsByClassName('form-control') then you will get array of elements when there are multiple inputs with same class.

As you asked to apply validation class, there must be some specific conditions/rules will be there to apply validation by your business logic. So I suggest you to apply class based on name/id attribute

document.querySelector('[name="digitar"]').classList.add('error')

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18975

The getElementsByClassName return array element need change to

let element = document.getElementsByClassName('form-control')[0];

let element = document.getElementsByClassName('form-control')[0];

document.getElementById("myBtn").addEventListener("click", function(){
    event.preventDefault()
    element.classList.add("error");
})
button {
    height: 50px;
    width: 200px;
    font-size: 28px;
    margin: 100px 0px;
}

.error {
    border: 2px solid red;
} 

.form-control {
    border-radius: 2px;
    font-size: 32px;
    width: 300px;
    height: 50px;
}
    <div>
        <form>
            <input type="text" name="digitar" id="digitar" class='form-control'><br>
            <button id='myBtn'>Clique aqui!</button>
        </form>
    </div>

Upvotes: 1

Related Questions