Blind Despair Blind Despair - 3 months ago 11
HTML Question

How to uncheck radio button in jquery using label

I have 3 buttons wrapped with labels of radio buttons, so basically control on radio is managed by those 3.

<input type="radio" name="block_image_checkbox" id="block_image_checkbox_1" value="a">
<label for="block_image_checkbox_1">
<div id="block_image_1" class="block_image block_image_hover">
<div class="block_image_overlay">
<img src="img/1-1.png" alt="" id="image"/>
</div>
</div>
</label>
<input type="radio" name="block_image_checkbox" id="block_image_checkbox_2" value="b">
<label for="block_image_checkbox_2">
<div id="block_image_2" class="block_image block_image_hover">
<div class="block_image_overlay">
<img src="img/2-1.png" alt="" id="image"/>
</div>
</div>
</label>


I use jquery to handle clicks on my buttons changing their view. My click handler is below.

$("#block_image_1").click(function() {
if(!$('.block_image_overlay').hasClass('block_image_overlay_active')){
$(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
$('.block_image').removeClass('block_image_hover');
}
else {
if($(this).children('.block_image_overlay').hasClass('block_image_overlay_active')){
$(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
$('.block_image').addClass('block_image_hover');
$('#block_image_checkbox_1').prop('checked', false);
}
else{
$('.block_image_overlay_active').toggleClass('block_image_overlay_active');
$(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
}
}
});


I want to uncheck radio button if I click on its label when it's checked. But it does not work. I think because when I try to uncheck it, it may get checked again. But is there any solution for this situation without using another button?

Answer

You can use Checkboxes for this, and if you want to have only one checkbox checked. you can write something like this

$("input[name='block_image_checkbox']").change(function(){
var curCheckBox = this;
	$("input[name='block_image_checkbox']").each(function(){
		if(this === curCheckBox)
			$(this).attr("checked",true);
		else
			$(this).attr("checked",false);
	});
});;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="block_image_checkbox_1" name="block_image_checkbox" value="no" />
<label for="block_image_checkbox_1"> checkbox1 </label>
<input type="checkbox" id="block_image_checkbox_2" name="block_image_checkbox" value="yes" />
<label for="block_image_checkbox_2"> checkbox2</label>
<input type="checkbox" id="block_image_checkbox_3" name="block_image_checkbox" value="yes" />
<label for="block_image_checkbox_3"> checkbox3</label>