简体   繁体   English

如何使用Ajax和PHP将复选框值传递给文本输入?

[英]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: 我正在尝试评估所有已选中复选框的值,并将结果传递给html文本输入。我正在尝试使用php和ajax进行此操作,但效果不佳,请帮助我编写以下代码:

    $(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 这是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 您可以使用此代码将值发送到服务器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 在你的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: 我认为您不需要使用total.php文件,但是如果您确实要使用它,我建议将代码更改为此:

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

The only change is the concatenation of the string you are printing 唯一的变化是要打印的字符串的串联

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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