I’m iterating over radio buttons previous neighbors. My html looks like this :
<div class="holder">
<span class="">some text</span>
<input type="radio" name="test_capability" value="primary" checked="" />
</div>
<div class="holder">
<span class="">some text</span>
<input type="radio" name="test_capability" value="primary" checked="checked" />
</div>
<div class="holder">
<span class="">some text</span>
<input type="radio" name="test_capability" value="primary" checked="" />
</div>
I’m trying to add class red to span whose neighbor radio button is checked. Here is how I tried :
$('.holder span').each(function(){
var spanElement = $(this);
if(spanElement.nextAll(':radio:first').is(':checked')){
spanElement.addClass("red");
}
});
I always end up with last span (the one in third holder div) having class red. But as you can see the middle one is checked. Same thing happens when I set checked=checked on first span
Update
Tried also :
$('.holder span').each(function(){
if($(this).next().attr("checked") == "checked"){
$(this).addClass("red");
}
});
Same result, don’t know what else to try.
Update II:
Html get rendered with previous information generated from server side, so there can only one checked=checked radio input element once html is created.
I’m doing this iteration trough span in document ready function.
You can select the checked input and add class to it’s sibling span element.
http://jsfiddle.net/TdR7k/
In case that you want to add and remove the classes on change event you can try the following:
http://jsfiddle.net/dSv6P/