I am having html like this:
<form>
<div class="row">
<input type="radio" class="radio">
<label>Text</label>
<input type="radio" class="radio">
<label>Type</label>
</div>
</form>
Now I need to apply a class to each label immediate after each <input type="radio">
.
I am using jquery like this:
if($('input').hasClass('radio')){
$(this).next().addClass('radio-url');
}
I am trying to add class 'radio-url' to each <label>
immediately after radio tag. What mistake have I did in this?
You can use .siblings()
$('input[type="radio"]').siblings('label').addClass('radio-url');
Or
$('input[type="radio"]').next('label').addClass('radio-url');
Try:
$(':radio').next().addClass('radio-url');
jsFiddle example (I threw a text input in there so you can see that it works on only radio inputs)
您可以使用next()函数
$("input:radio").next('label').addClass("radio-url");`
This answer doesn't directly answer your question!
I believe that your label should have the for attribute so that the label is associated with the radio button. This allows the user:
HTML
<div class="row">
<input type="radio" class="radio" id="text"></input>
<label for="text">Text</label>
<input type="radio" class="radio" id="type"></input>
<label for="type">Type</label>
</div>
JQuery
Search the label using the radio element's ID.
$('input[type="radio"]').each(function(){
var radioId = $(this).attr("id");
$("label[for='" + radioId + "']").addClass('radio-url');
});
Fiddle: http://jsfiddle.net/78zAB/
You need to loop through all radio buttons:
$('input[type="radio"]').each(function(){
$(this).next().addClass('radio-url');
});
Or
$("input[type='radio'] + label").addClass('radio-url')
$('input.radio').each(function () {
$(this).next().addClass('radio-url');
})
Use CSS element+element selector:
$('input:radio + label').addClass('theClass')
Works optimal
$('input[type=radio]').next('label').addClass('radio-url');
Posting this as an answer as all of the others are using the incorrect selector, or don't specify the label
in next()
:
$('input.radio').next('label').addClass('radio-url');
.. which will add the class radio-url
to all label
elements which come immediately after an input
with the class radio
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.