简体   繁体   中英

How to post multiple <input type=“checkbox” /> as array in PHP?

So that in PHP I can deal with them as :

foreach($_POST['checkboxname'] as $i => $value)
...

Do something like this:

<input type="checkbox" name="checkboxArray[]" />

Note the [] in the name.

Like this:

<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />
<input type="checkbox" name="checkboxname[]" />

Just append [] to their names.

如果将数组用于复选框,则应添加一个值选项作为单个复选框的标识符,因为返回的数组将从Array([0] => on,[1] => on)变为Array([0 ] => value1,[1] => value5),可让您识别选中的复选框。

for those HTML form elements that can send multiple values to server (like checkboxes, or multiple select boxes), you should use an array like name for your HTML element name. like this:

<input type="checkbox" name="checkboxname[]" />

also it is recommended that you use an enctype of "multipart/form-data" for your form element.

<form enctype="multipart/form-data" action="target.php" method="post">

then in your PHP scripts you can access the multiple values data as an array, just like you wanted.

 <html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(even){ $("button").click(function(){ var checkvalue = []; $.each($("input[name='1']:checked"), function(){ checkvalue.push($(this).val()); }); alert("checkvalue: " + checkvalue.join(", ")); }); }); </script> <body> <input type="checkbox" name="1" value="1" > 1 <br/> <input type="checkbox" name="1" value="2"> 2 <br/> <input type="checkbox" name="1" value="3"> 3 <br/> <button type="button">Get Values</button> </body> </html> 

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