I’m trying to use images as checkboxes. The following would work fine if it were radios instead of checkboxes that I was targeting but with checkboxes the problem is I can’t select an element by clicking on it again after selecting it.
// image checkbox
$('#imageCheckBoxes img').click(function() {
$(this).parent('span').find('input:checkbox').attr('checked', 'checked');
});
<div id="imageCheckBoxes">
<ul>
<li><a href="">Africa</a> <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
</li>
<li><a href="">Asia/Pacific Islands</a> <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
</li>
<li><a href="">Australia</a> <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
</li>
<li><a href="">Central/South America</a> <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
</li>
<li><a href="">Europe/Russia</a> <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
</li>
<li><a href="">North America</a> <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
</li>
<li><a href="">United Kingdom</a> <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
</li>
</ul>
</div>
I need to basically toggle the check attr() part.
How to do that?
I’d do this by passing a function to
prop(since jQuery 1.6,attrbefore). The return value of this is set as the new property value.The key fact here is that you can pass
trueorfalsetopropto set thecheckedproperty.oldPropis the existing value of the property (which will be eithertrueorfalse), so!oldPropis the inversion: checked elements are unchecked and vice versa.Note that I have also changed your code to look for the closest ancestor
lielement withclosest, which should be more reliable and effective.