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 >
<fieldset>
<legend>First name</legend>
<input type="text" name="firstname" placeholder="First name" required>
</fieldset>
</div>
<div >
<fieldset>
<legend>Last name</legend>
<input type="text" name="lastname" placeholder="Last name" required>
</fieldset>
</div>
<div >
<fieldset>
<legend>Email</legend>
<input type="email" name="email" placeholder="Email" required>
</fieldset>
</div>
<input type="submit" id="submit" value="Send">
CodePudding user response:
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.
CodePudding user response:
Try targeting the parent fieldset
explicitly by using the parent
selector. (And also cache the jQuery'd this
var.)
$('#submit').click(function(e) {
e.preventDefault();
$('input').each(function() {
var $this = $(this);
if ($this.hasClass("error")) {
$this.parent("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 >
<fieldset>
<legend>First name</legend>
<input type="text" name="firstname" placeholder="First name" required>
</fieldset>
</div>
<div >
<fieldset>
<legend>Last name</legend>
<input type="text" name="lastname" placeholder="Last name" required>
</fieldset>
</div>
<div >
<fieldset>
<legend>Email</legend>
<input type="email" name="email" placeholder="Email" required>
</fieldset>
</div>
<input type="submit" id="submit" value="Send">