使用PHP / Javascript在复选框中传递多个值

Is it possible to pass multiple values with a checkbox submit. I need to pass the value and the data-export to the insert statement in php? Is it possible in PHP?

Example (HTML):

<input type="checkbox" data-export="<?= $list1['export_charges']; ?>"  name="chk_export[exportinr]"  value="<?= $list1['export_charges_inr']; ?>">

In PHP:

 $exportinr = $_POST['chk_export']['exportinr'];

Here's one solution for it

<input type='checkbox' value='.$list1['export_charges_inr'].' name="chk_export[]" />
<input type='checkbox' value='.$list1['export_charges'].' name="chk_export[]" />

Php code to get the values

$numb = count($chk_export);
for($i=0;$i<=($numb - 1);$i++){
    echo $chk_export[$i];
}

One more solution is

<input type="checkbox" value="'.$list1['export_charges'].':'.$list1['export_charges_inr'].'" name="chk_export" />

In php

$pieces = explode(":", $_POST['chk_export']);
echo $pieces[0];
echo $pieces[1];

Either use a delimiter like so:

<input value="value#data-export-value" name="somefield">

Then in PHP:

list($value, $dataexport) = explode("#", $_POST["somefield"]);
// $value and $dataexport will hold the appropriate values

Or try it with a library, e.g. jQuery:

$("#formName").on('submit', function(evt) {
    evt.preventDefault();
    var fieldvalue = $("#somefield").val();
    var fielddata = $("#somefield").data('export');
    var data = {fieldvalue: fieldvalue, fielddata: fielddata};
    $.ajax({
        type: "POST",
        url: url,
        data: data
    });
});

In PHP, you will have access to fieldvalue & fielddata like so:

$fieldvalue = $_POST["fieldvalue"]; 

If you have never worked with jQuery before, better use the delimiter solution.

I think with current code, it will pass only one value,

name="chk_export[exportinr]"

change it like this

name="chk_export[exportinr][]"

or

name="chk_export[]"

data-* attributes are designed to be handled by client side code.

If you want to submit two or more values you can have other solutions like:

  1. Use hidden input fields to hold the other values.
  2. use a custom made pattern of your values and post them i.e

    <input type="checkbox" name="chk_export" value='.$list1['export_charges'].'-'.$list1['export_charges_inr'].'>
    

and on the PHP side receive the post value and explode it at '-'

    $arr = explode("-", $_POST["chk_export"]);

Your input tag should be like this

<input type="checkbox" data-export='.$list1['export_charges'].' name="chk_export[exportinr][]"  value='.$list1['export_charges_inr'].'>

Now to get value of each check box you have to use php for loop something like this:

$N = count($_POST['chk_export[exportinr][]']);

for($i=0; $i < $N; $i++)
{
  echo($_POST['chk_export[exportinr][$i]']);
}