I have 2 checkboxes for yes/no. The checkboxes will hide a div based on the checkbox that is checked. I have a function that works using IDs for selectors however I will have multiple of these pulled in dynamically and need this function to use classes to select closest classes to the checkbox that is clicked.
This function works using IDs but I want to use classes: http://jsfiddle.net/infatti/mNQK7/
$('#solutionImplemented1').click(function () {
// uncheck the other checkbox and hide other content if this is checked
if (this.checked) {
$('#solutionImplemented2').attr('checked',false);
$('#solutionImplementedContent2').hide(this.checked);
}
// show correct content
$('#solutionImplementedContent1').toggle(this.checked);
});
$('#solutionImplemented2').click(function () {
// uncheck the other checkbox and hide other content if this is checked
if (this.checked) {
$('#solutionImplemented1').attr('checked',false);
$('#solutionImplementedContent1').hide(this.checked);
}
// show correct content
$('#solutionImplementedContent2').toggle(this.checked);
});
This is not working but needs to use selectors relative to checkbox clicked: http://jsfiddle.net/infatti/n6gW5/
$('.check-hide-show input:checkbox').click(function () {
var firstCheckbox = $(this).parent().find('input:checkbox').eq(0);
var secondCheckbox = $(this).parent().find('input:checkbox').eq(1);
var checkboxContent1 = $(this).parent().find().nextAll('.check-hide-show-content:gt(0)');
var checkboxContent2 = $(this).parent().find().nextAll('.check-hide-show-content:gt(1)');
// uncheck the other checkbox and hide other content if this is checked
if ($(firstCheckbox).checked) {
$(secondCheckbox).attr('checked',false);
$(checkboxContent2).hide();
$(checkboxContent1).show();
}
});
How can I select elements relative to checkbox clicked? What am I not doing right here?
You’re going to find this method incredibly hard to maintain. Imagine what happens if you have 50 checkboxes; 50 if statements with 50 lines of
.hide()and.show()? What I’d suggest is having each checkbox linked to itsdiv, perhaps through aname=attribute.Then, you could do:
Then, in your code:
Since jsFiddle is currently down for me, here’s an example on jsBin. Note that if you check both checkboxes, it will only use the latest checked one. You can circumvent that by adding:
(Update: Here it is on jsFiddle.)