简体   繁体   中英

how to pass checkbox value to text input using Ajax and PHP?

I'm trying to evaluate the values of all checked checkboxes and pass the result to html text input I'm trying to do that using php and ajax but I have no good result please help this is my code:

    $(document).ready(function ()
          {

            $("#check").click(function ()
            {
                var data = $("#check").val();
                //get selected parent option 

                $.ajax(
                        {
                            type: "GET",
                            data:data,
                            url: "total.php?val="+data,

                            cache: false,
                            success: function (data)
                            {

                                $("#tot").html(data);
                            }
                        });
            });

        });
    </script>

</head>
<?php

$conn = mysqli_connect("localhost", "root", "", "voucher_test");

    $result = mysqli_query($conn, "SELECT * FROM vouchers where cat_id = 1");
    while ($row = mysqli_fetch_array($result)) {
        $userSet[] = $row;
    }

    ?>  

<form   action="index.php" method="post">
    <?php
            foreach ($userSet as $key=>$value){
                echo $value['service_name']."<input type='checkbox' id='check'  name='{$value['service_name']}' value='{$value['service_price']}'>";

            }
    ?>
    <br>
    <div id="tot"></div>
</form>

and this is total.php

    <?php
      $itot = 5;
      $itot+=$_GET['val'];
      echo"<input type='text' value='$itot'>";

You can use this code to sent value to server y o n

var data = ($("#check").is(":checked") ? 'y' : 'n';

If you want send the value of checkbox, try this code:

var data = new FormData();//Create FormData

if($("#check").is(":checked")){//Verified if the input os checked
    data.append('data-check',$("#check").val());//Add data of the checkbox to FormData
}

$.ajax(
     {
        type: "GET",
        data: data,
        url: "total.php",
        cache: false,
        success: function (data)
                {
                    $("#tot").html(data);
                }
});

In yur php

$_GET['data-check'];

I don't think you need to use the total.php file, but if you really want to use it I recommend to change your code to this:

<?php
  $itot = 5;
  $itot+=$_GET['val'];
  echo"<input type='text' value='" . $itot . "'>";

The only change is the concatenation of the string you are printing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM