-1

I have the following checkboxes in an HTML form.

<ul id="selection">
  <span><label>First<br><input type="checkbox" name="First"></label></span>
  <span><label>Second<br><input type="checkbox" name="Second"></label></span>
  <span><label>Third<br><input type="checkbox" name="Third"></label></span>
  <span><label>Fourth<br><input type="checkbox" name="Fourth"></label></span>
  <span><label>Fifth<br><input type="checkbox" name="Fifth"></label></span>
</ul>

I'm trying to create two buttons. One that would select the first two and one that would select all of them.
I managed to select all of them with one button using this:

<input type="button" class="check btn" onClick="select(this)" value="Select All"/>
    <script>
      $('.check:button').click(function(){
          var checked = !$(this).data('checked');
          $('input:checkbox').prop('checked', checked);
          $(this).val(checked ? 'uncheck all' : 'Select' )
          $(this).data('checked', checked);
      });
    </script>

But I can't seem to get the two buttons working.
My JavaScript knowledge is pretty limited and been searching for days, unsuccessfully for a solution that works.
Can please someone help? a detailed explanation would be awesome.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
o_ren
  • 772
  • 1
  • 7
  • 14

2 Answers2

1

Try this:

$("#selectall").click(function() {
  $("input[type='checkbox']").prop('checked', true);
});
$("#selecttwo").click(function() {
  $("input[name='First'], input[name='Second']").prop('checked', true);
});
$("#resetall").click(function() {
  $("input[type='checkbox']").prop('checked', false);
});

DEMO

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97
0

Are you looking for this, https://jsfiddle.net/wx38rz5L/1261/ ( sorry about css :P ) or https://jsfiddle.net/wx38rz5L/1262/

Reference: https://api.jquery.com/attribute-equals-selector/

$('input[name=First]').prop('checked',true);
$('input[name=Second]').prop('checked',true);

//$('input[name=First],input[name=Second]').prop('checked',true); in one line
Gopinath Shiva
  • 3,822
  • 5
  • 25
  • 48