skip to Main Content

My script doesn’t work for multiple checkboxes, it only returns 1 value, not according to what is checked. Where’s the mistake?

Javascript/jQuery:

    <script type="text/javascript">
    function getProsesAlo() {
      var cblist = { 'period[]' : []};
      $(":checked").each(function() {
        cblist['period[]'].push($(this).val());
    });
    $.post("proses-alokasi.php", {
      nama: frmProses.fnama.value,
      prono: frmProses.fprono.value,
      thn: frmProses.ftahun.value,
      cblist
    },
    function(output) {
        $("#statusmsg").html(output).fadeIn(1000); 
    });
    }
   </script>

HTML Form:

<input type="text" name="fprono">
<input type="text" name="fnama">
<select id="tahun" name="ftahun" class="form-control form-control-md">
    <option value="">Tahun:</option>
    <?php
    for ($i=$tahun; $i >= $tahunmin; $i--){
    ?>
    <option value="<?=$i;?>"><?=$i;?></option>
    <?php
    }
    ?>
</select>
<input type="checkbox" name="period[]" value="1">
<input type="checkbox" name="period[]" value="2">
..
<input type="checkbox" name="period[]" value="12">
<input type="button" value="Proses" id="proses" onClick="getProsesAlo<?=$no;?>()">
<!----- Result ----->
<div id="statusmsg">Unprocessed</div>

PHP code proses-alokasi.php:

    <?php
    $prono = $_POST['prono'];
    $namaang = $_POST["nama"];
    $jiuran = $_POST["jiuran"];
    $thn = $_POST["thn"];
    $periode = $_POST['cblist'];
   
    if(!empty($_POST['cblist'])) {
        // Counting number of checked checkboxes.
        $checked_count = count($_POST['cblist']);
        // Loop to store and display values of individual checked checkbox.
        foreach($_POST['cblist'] as $pilihperiod){
        echo "<p>".$pilihperiod ."</p><br>";
            echo "<p>".$pilihperiode."</p><br>";
        }
    } else {
        echo "<b>Please Select At least One Option.</b>";
    }
    ?>

Please help, your answer will be very helpful, thank you.

2

Answers


  1. Chosen as BEST ANSWER

    Solved.

    I change:

    var cblist = { 'period[]' : []};
          $(":checked").each(function() {
            cblist['period[]'].push($(this).val());
        });
    

    to:

    var cblist = $('input:checkbox:checked').map(function(){
                   return this.value;
                  }).get();
    

  2. Use:

    var cblist = {"period" : []};
    $(":checked").each(function() {
      cblist.period.push($(this).val());
    });
    

    to collect the checked values, otherwise PHP will receive the subkey of cblist in a wrong format (not array) and therefore will only take the last value

    Also use $(":checkbox:checked") as checkbox selector, otherwise select value will be included too

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search