I need to add css to a sibling select element of a span element only if the span element has content.
The html is this:
<td class="ruleField">
<select name="rules[field][]" class="form-select " >
<option value="0">-- Select --</option>
<option value="554">Identifier</option>
<option value="548">Display Name</option>
</select>
<span class="rules-error">Not allowed.</span>
</td>
This works:
if( $('.rules-error').text().length>0){
$('.rules-error').siblings().css('background-color','green')
}
but i need it to be specific to that spans sibling select.
But this does not work:
if( $('.rules-error').text().length>0){
$(this).siblings().css('background-color','green')
}
2
Answers
It’s a bit hard to see what code is around your if statement, but in the case of your last code,
this
does not refer to your.role-error
element, so you can do something like this:Demo
The first issue in your code is that
$(".rules-error").text()
combines all the text from all the.rules-error
elements into a single string, so if one has an error, then your code treats it as all have errors.Clearest option is to loop through each
.rules-error
and check, which gives you the context inthis
(code already provided in another answer).You can make this more succinct by using
.filter
. If your rules-error spans are always blank, you could use:but whitespace counts as being not-empty, so this will fail for
<span> </span>
(or a newline if you’re html is formatted as such) – so you need to trim this in the filter.Note: this is essentially the same as looping, it just pre-loops and the applies the css to all the matching elements at once. I also suggest adding a class for the style rather than using
.css()
as it will be easier to simply remove the class when you want to clear the errors.Updated snippet: