mardi 19 février 2019

how to pass values of several checkboxes with jquery ajax

To get the value from several checkboxes i use this code:

 <form class="myform" method="post" action="">
        <input type="checkbox" class="checkbox" value="11" /><br>
        <input type="checkbox" class="checkbox" value="22" /><br>
        <input type="submit" value="Go" />
  </form>

The ajax:

$(document).ready(function(){
            $('.myform').on('submit', function(e){
                //Stop the form from submitting itself to the server.
                e.preventDefault();
                var checkboxvalue = $('.checkbox').val();
                $.ajax({
                    type: "POST",
                    url: '',
                    data: {checkboxvalue: checkboxvalue},
                    success: function(data){
                        $('.response').html(data);
                    }
                });
            });
        });

The php:

   if($_SERVER['REQUEST_METHOD'] == "POST") {  

      $value = false;
      if(isset($_POST['checkboxvalue'])){
         $value = $_POST['checkboxvalue'];
      }

      echo 'The value was: ' . $value;
      exit;
   }

The problem is: when checking the second checkbox, i get the value 11 , thats the value of the first checkbox. When clicking both checkboxes, i also get the value 11

What i want to achieve: if i check the first checkbox, het should give me 11 as output. Checking the second checkbox, he should output 22 as value. And when checking both checkboxes, he should output 11 and 22 as value.

How can i achieve this?




Aucun commentaire:

Enregistrer un commentaire