2

I'm trying to have a checkbox called 'All' that when checked, also checks the rest of the checkboxes in my form. I have basically no javascript experience so sorry if this is really basic. I patched this together from looking at posts like this and this.

<script type="text/javascript">
function checkIt(checkbox)
{
  document.GetElementById("1").checked = true;
  document.GetElementById("2").click();

}
</script>

My HTML looks like this:

<form>
  <input type="checkbox" id="A" onclick="checkIt(this)">All<br></input>
  <input type="checkbox" id="1">One<br></input>
  <input type="checkbox" id="2">Two<br></input>
</form>

How can I get checkboxes 1 and 2 to change when I select checkbox All? Thanks.

Community
  • 1
  • 1
taronish4
  • 504
  • 3
  • 5
  • 13

1 Answers1

-2

Since you are not familiar with javascript, I suggest looking into the jQuery javascript library. Many coders find it simpler to learn/use, and there is no debate that it requires MUCH less typing.

Here are some introductory jQuery tutorials if you are curious.

To solve your problem, I added a class to the checkboxes that you wish to automatically check/uncheck, and used that class to check/uncheck the boxes.

Working jsFiddle here

HTML:

<form>
  <input type="checkbox" id="A">All<br></input>
  <input type="checkbox" class="cb" id="1">One<br></input>
  <input type="checkbox" class="cb" id="2">Two<br></input>
</form>

JQUERY:

$('#A').click(function() {
   // alert($(this).prop('checked'));
    if ($(this).is(':checked') == true) {
        $('.cb').prop('checked', true);
    }else{
        $('.cb').prop('checked', false);
    }
});

Note that this solution uses jQuery, so you need the jQuery library loaded (usually put this line in your head tags):

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
cssyphus
  • 37,875
  • 18
  • 96
  • 111