jQuery add class to fieldset if input is have error class

Issue

How can I add "error" class to the fieldset(s) too if their input’s are have "error" class?

I’m trying to achieve this as the following, but it’s adding the "error" class to every fieldsets no matter if the input is have the "error" class or not.

$('#submit').click(function(e) {
    e.preventDefault();
    $('input').each(function() {
        if($(this).hasClass("error")){
            $("fieldset").addClass("error");
        }
    });
});
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="form-holder">
    <fieldset>
        <legend>First name</legend>
        <input type="text" class="form-control" name="firstname" placeholder="First name" required>
    </fieldset>
</div>

<div class="form-holder">
    <fieldset>
        <legend>Last name</legend>
        <input type="text" class="form-control error" name="lastname" placeholder="Last name" required>
    </fieldset>
</div>

<div class="form-holder">
    <fieldset>
        <legend>Email</legend>
        <input type="email" class="form-control error" name="email" placeholder="Email" required>
    </fieldset>
</div>

<input type="submit" id="submit" value="Send">

Solution

The code is doing what you are telling it to. When you say $("fieldset").addClass("error"); it means to add the error class to all fieldset elements.

What you need to do is find the fieldset that is the parent of the input which has the error class. In your example this would be:

$('#submit').click(function(e) {
    e.preventDefault();
    $('input').each(function() {
        if($(this).hasClass("error")){
            $(this).closest("fieldset").addClass("error");
        }
    });
});

The closest() method will travel up the DOM looking for the first element which matches the selector. So it should find the closest fieldset parent to the input.

Answered By – Daniel Black

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.