Reputation: 91
I'm radio buttons on my webpage as a filter and the radio buttons are hidden, I just showing the labels. The code looks like this:
<div class="filter">
<div class="field_row label-selected">
<input id="field_6_95_0" class="filteDataForSerialize" type="radio" value="0" name="f[g][6]">
<label for="field_6_95_0">Option 1</label>
</div>
<div class="field_row">
<input id="field_6_95_1" class="filteDataForSerialize" type="radio" value="1" name="f[g][6]">
<label for="field_6_95_1">Option 2</label>
</div>
<div class="field_row">
<input id="field_6_95_2" class="filteDataForSerialize" type="radio" value="2" name="f[g][6]">
<label for="field_6_95_2">Option 3</label>
</div>
</div>
And I'm using the following script:
jQuery('.filter div:first').addClass('label-selected');
jQuery('.filter label').on('click', function() {
var parent_div = jQuery(this).parent().addClass('label-selected');
jQuery('.filter').find('div').not(parent_div).removeClass('label-selected');
});
So by default the first element got the label-selected class and when I'm choosing any other that will got the class and the script delete from the other. It works until I'm using the same html snippet in the same page more times. In this case the jQuery remove every label-selected class from the page.
Css doesn't affect it I think, but:
.field_row > input{display:none};
.field_row > label{display:block;cursor:pointer;padding: 5px 10px;}
.label-selected > label{bacground-color:#000;color:#fff;}
Upvotes: 0
Views: 1718
Reputation: 373
You can remove the class from all the label's parent's siblings.
jQuery('.filter label').on('click', function() {
var parent_div = jQuery(this).parent().addClass('label-selected');
parent_div.siblings().removeClass('label-selected');
});
Upvotes: 2