Dima Vleskov Dima Vleskov - 3 months ago 5
Javascript Question

if one checkbox is checked, how to uncheck another?

I have some problems with my calculator, I have five checkboxes (costOne, costTwo, costThree, costFour, costFive)

When I check costOne, then costTwo should turn off, but if I click on this costTwo (which then is turned off) then costOne should be turned off.

My code works only partly: when I click on the costOne, then you cannot click on the costTwo anymore (because it becomes disabled), but when I click on costOne it turns off and costTwo turns on at the same time - this is exactly what I want.

But I can't click costTwo.

This is a link to my site http://ot.sysale.ua/#/business-protect.

The first and the third input I need to have this linked behaviour.

Here is the relevant code:

//calculator
var init = $('.switch input').on('click', function() {
var value1 = 0;
var value2 = 0;

var costOne = $("#cost-one"),
costTwo = $("#cost-three");


if (costOne.is(':checked')) {
costOne.prop("checked", true);
costTwo.prop("checked", false);
} else {
costOne.prop("checked", false);
costTwo.prop("checked", true);
}

init.filter(':checked').closest('tr').each(function() {
value1 += (+$(this).find('span.cost-one').text());
value2 += (+$(this).find('span.cost-two').text());
});

$('.counter-one span').eq(0).html(value1 + ' ');
$('.counter-two span').eq(0).html(value2 + ' ');
});

Answer

You could use this code (simplified to focus on the issue):

$('input').on('change', function(){
    var id = $(this).prop('id');
    if (id == 'cost-one' || id == 'cost-three') {
        // Make sure the two have opposite values:
        var other = id == 'cost-one' ? 'cost-three' : 'cost-one';
        $('#'+other).prop("checked", !$(this).prop("checked"));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
One: <input type="checkbox" id="cost-one"><br>
Two: <input type="checkbox" id="cost-two"><br>
Three: <input type="checkbox" id="cost-three" checked><br>

The other variable will identify the id of the other checkbox: if you clicked on cost-one, it will refer to cost-three, and vice versa.

Then that other checkbox will get the opposite checked state.

To be consistent, you should also check one of the two on page load, so I have added the checked attribute for the third checkbox.

As has been expressed in comments, this behaviour is standard with radio buttons. So, unless your library does not support the same widget-look for it, you could maybe better use those instead (for those linked items).

Comments