Reputation: 27
I am trying to dinamically set the attribute filter-by
to each Radio Button inside a page, and set the value of this attribute based on the text inside each Span Element next to them.
I came up with this
$(document).ready(function() {
$(':radio').attr('filter-by', $(this).next().text());
});
But it's not setting the attribute value.
This is the HTML snippet
<label>
<input type="radio" filter-by="">
<span>Text</span>
</label>
I'm expecting <input type="radio" filter-by="Text">
Upvotes: 0
Views: 41
Reputation: 777
You try to use
$(document).ready(function() {
$('input[type="radio"]').each(function(){
$(this).attr('filter-by', $(this).next().text());
});
});
Upvotes: 1
Reputation: 27051
You have to do it like this, because in your attempt $(this)
would not refer to your :radio
$(':radio').attr({'filter-by': function() {
return $(this).next().text()
}});
Demo
$(document).ready(function() {
$(':radio').attr({'filter-by': function() {
return $(this).next().text()
}});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" filter-by="">
<span>Text</span>
</label>
Upvotes: 2