I'm trying to add a class to the parent div which is <div class="form-group"> i got it to work, but was wondering if there was a shorter or simpler way to do so? Here is my 2 HTML situations
HTML:
<div class="form-group">
<label class="col-md-3 control-label required" for="Comment_postcode">Your Postcode <span class="required">*</span></label>
<div class="col-md-9 error">
<span style="position: relative; display: inline-block;" class="twitter-typeahead">
<input style="position: absolute; top: 0px; left: 0px; border-color: transparent; box-shadow: none; background: none repeat scroll 0% 0% rgb(255, 255, 255);" class="tt-hint" autocomplete="off" spellcheck="off" disabled="" type="text"/>
<input dir="auto" style="position: relative; vertical-align: top;" spellcheck="false" autocomplete="off" class="form-control tt-query" name="Comment[postcode]" id="Comment_postcode" type="text"/>
</span>
</div>
</div>
and
<div class="form-group">
<label class="col-md-3 control-label required" for="Comment_purchased">This vehicle was purchased <span class="required">*</span>
</label>
<div class="col-md-9 error">
<select id="Comment_purchased" class="form-control input-md">
<option value="">Select One</option>
<option value="1">New</option>
<option value="2">Used</option>
</select>
<div class="errorMessage" id="Comment_purchased_em_" style="display:none">Purchased cannot be blank.</div>
</div>
</div>
this is my JQuery code to add or remove the has-error class
if (i != "Comment_postcode") {
$("#"+i).parent("div").parent("div").addClass("has-error");
} else {
$("#"+i).parent("span").parent("div").parent("div").addClass("has-error");
}
how would i optimize the code above? if possible without the if-else statement. Thanks
use closest to get closest parent
$("#"+i).closest(".form-group").addClass("has-error");
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
you also can use parents()
$("#"+i).parents(".form-group").addClass("has-error");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With