Shiny Hunter Rob
Shiny Hunter Rob

Reputation: 101

Two checkboxes acting as one

I have two checkboxes on a page and I want them to act as only one. For example, I select one, and the other is selected automatically, and vice-versa. I've managed to select both of them at once, but I can't seem to figure out a way to deselect them at once.

And what's bothering me the most, is that it's probably a super simple line of code that I'm simply not remembering.

Is there a way to do this?

Upvotes: 0

Views: 224

Answers (4)

Ashwin
Ashwin

Reputation: 270

$(document).ready(function() {
	$('#check_one').change(function() {
  	$('#check_two').prop('checked', $('#check_one').prop('checked'));
  });
  
	$('#check_two').change(function() {
    $('#check_one').prop('checked', $('#check_two').prop('checked'));
  });  
});
<form>
<label>Simple checkbox</label>
<input type="checkbox" id="check_one" />
<label>Complicated checkbox</label>
<input type="checkbox" id="check_two" />
</form>

Assuming you have two checkboxes named differently but working in concert, this code would work

Upvotes: 1

VTr
VTr

Reputation: 718

Here is a solution in pure javascript:

// Select all checkboxes using `.checkbox` class
var checkboxes = document.querySelectorAll('.checkbox');

// Loop through the checkboxes list
checkboxes.forEach(function (checkbox) {
    // Then, add `change` event on each checkbox
    checkbox.addEventListener('change', function(event) {
        // When the change event fire,
        // Loop through the checkboxes list and update the value
        checkboxes.forEach(function (checkbox) {
            checkbox.checked = event.target.checked;
        });
    });
});
<label><input type="checkbox" class="checkbox"> Item 1</label>
<br>
<label><input type="checkbox" class="checkbox"> Item 2</label>

Upvotes: 1

TypedSource
TypedSource

Reputation: 708

html:

<input type="checkbox" id="1" class="handleAsOne">
<input type="checkbox" id="2" class="handleAsOne">

javascript (jquery):

$('.handleAsOne').on('change'){
   $('.handleAsOne').prop('checked', false);
   $(this).prop('checked', true);
}

if i understood your question correctly you are looking for something like this.

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35011

Is this what you're looking for?

$(".test").change(function () {
    $(".test").attr("checked", this.checked);
  });

<input type='checkbox' class='test'>A<br />
<input type='checkbox' class='test'>B<br />

Upvotes: 1

Related Questions