Dejell Dejell - 3 months ago 51
CSS Question

Deselect bootstrap 3 radio button on second click

I would like to allow deselect a bootstrap btn-group radio button without an extra button.

Following this answer, I wrote jsfiddle but it doesn't work for me. Why?
I see by looking at the log that the method is being called on second time click.

$('body').on('click', '.btn.active', function(e){
console.log("test");
e.stopImmediatePropagation();
$('input:radio[name="options"]').parent().removeClass("active");
})


HTML:

<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked/>Radio 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off">Radio 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off">Radio 3
</label>
</div>

Answer

Here is a working fiddle. For some reason you have to call both stopPropagate and preventDefault to make it work.

$('body').on('click', '.btn.active', function(e){
    e.stopImmediatePropagation();
    e.preventDefault();
    console.log(this, $('input:radio[name="options"]', this));
    $(this).removeClass('active');
    $('input:radio[name="options"]', this).prop('checked', false);
})
Comments