dennis ramli
dennis ramli

Reputation: 73

all checked when first checkbox checked

i have a problem with checkbox . i want to check all when the first checkbox is checked. this is my code

<tr>
    <td><label for="">Pilih Pendidikan</label></td>
    <td style="text-align:left;">
    <input type="checkbox" id="pilih_semua_pdk">Pilih Semua
    <?php foreach ($query2 as $row2) {?>
      <input class="form-control required check_pdk" type="checkbox" name="pendidikan[]" value="<?php echo $row2[id_pendidikan]; ?>"
          <?php
            $pendidikan = $_POST[pendidikan];
              if ($pendidikan !=NULL) {
                  foreach($pendidikan as $pendidikan){
                    if ($pendidikan == $row2[id_pendidikan]) {
                      echo "checked";
                    }
                }
              }
          ?>
      ><?php echo $row2[nama_pendidikan]; ?>
    <?php  } ?>
    </td>
</tr>

i try this code but doesnt work

<script>
   $("#pilih_semua_pdk").click(function () {
       $(".check_pdk").prop('checked', $(this).prop('checked'));
</script>

Upvotes: 0

Views: 239

Answers (2)

asprin
asprin

Reputation: 9823

jQuery makes this a piece of cake.

$(document).ready(function(){
    // DOM has been loaded, attach click event for first checkbox

    $('#pilih_semua_pdk').on('click', function(){
        // verify if it is checked
        if($(this).is(':checked'))
        {
            // check/tick the remaining checkboxes of the same td
            $(this).siblings('.check_pdk').prop('checked', 'checked');
        }
        else
        {
            // do something when the first checkbox is unchecked
        }
    });
});

Upvotes: 0

ScanQR
ScanQR

Reputation: 3820

Try this, you need to bind an click event on first checkbox. On click of the first checkbox check if that is checked!. If yes then find all checkbox to get going.

$('#pilih_semua_pdk').on('click', function(){
    if( $(this).is(':checked'))
    {
      //find parent td and its all checkboxes excluding first
      $(this).parent().find('input[type=checkbox]').not('#pilih_semua_pdk').each(function(){
           $(this).prop('checked', true);
      });
    }
});

Upvotes: 1

Related Questions