Reputation: 7
I'm trying to traverse through <td>
elements to get the sibling radio boxes so that only one image can be selected at a time (I'm using the following example but added inputs into a table for formatting purposes http://jsfiddle.net/yijiang/Zgh24/1/):
HTML:
<div id="divid">
<table>
<tr>
<td><input type="radio" name="test1" id="test1" value="1" /><label>IMAGE</label></td>
<td><input type="radio" name="test2" id="test2" value="4" /><label>IMAGE</label></td>
</tr>
</table>
</div>
jQuery:
<script>
$('#divid input:radio').addClass('input_hidden');
$('#divid label').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>
I'm not sure how to traverse correctly to ensure only one image can be selected at a time within the <td>
elements - I've tried the following but it doesn't work:
$(this).addClass('selected').parent('td').find('label').removeClass('selected');
Any ideas?
Upvotes: 0
Views: 59
Reputation: 34416
In your fiddle it is just a matter of choosing the right siblings - http://jsfiddle.net/Zgh24/1248/
$('#sites label').click(function () {
$(this).addClass('selected').siblings('label').removeClass('selected');
});
For your table example above you have to approach it a little differently, because doing it all in one chained group causes the selected item to have the class removed as well.
$('#divid label').click(function() {
$(this).closest('tr').find('label').removeClass('selected');
$(this).addClass('selected');
});
http://jsfiddle.net/Zgh24/1249/
Upvotes: 0
Reputation: 2865
The easiest way to do something like this is to remove the class from all elements, and then add it to the one you need it added to.
So something like this should work:
$('.selected').removeClass('selected');
$(this).addClass('selected');
Upvotes: 0
Reputation: 67207
Try to remove the class .selected
from the label
elements which is being set with .selected
class and then add .selected
class to the current element,
$('#divid label').click(function(){
$('label.selected').removeClass('selected');
$(this).addClass('selected');
});
Upvotes: 1
Reputation: 360692
Your radio inputs have different names. That means they can be selected at the same time, since they're DIFFERENT radio buttons. If you had
<input type="radio" name="foo" value="1" />
<input type="radio" name="foo" value="2" />
Then the browser would automatically deselect one when the other is selected.
Upvotes: 0