Page 1 of 1

HTML select with multiple attribute

Posted: Wed Jan 15, 2014 7:09 pm
by Lou
Got a question about html form, Select and options.
One of the <select> attributes is multiple, a "Boolean attribute allows multiple selections." My problem is I can't figure out how to capture the multiple values on the server side handler called when the form is submitted. In fact I can't see that multiple values are passed. W3C doesn't seem to define who multiple values are passed, they just say they are.

If in fact the values are passed as W3schools (a fount of questionable information) implies on
http://www.w3schools.com/tags/tryit.asp ... t_multiple
that the passed label/value pairs in our case would be something like list=Two&list=Four&list=Six
So we end up with the array $_POST (or $_GET) with more than one element with the same key, which can't be.

Any suggestions/source to read?

Two simple code fragments to illustrate the issue are:

Code: Select all

   <form action="test2.php" method="POST">
      <select multiple size='5' name='list'>
         <option>One</option>
         <option>Two</option>
         <option selected>Three</option>
         <option>Four</option>
         <option>Five</option>
         <option>Six</option>
      </select>
      <input type="hidden" name="other" value="hide">
      <input type="submit">
   </form>
Which calls

Code: Select all

<?php
   
   echo "<br>" . count($_POST) . "<br>";
   $keys = array_keys($_POST);
   for ($i=0; $i<count($keys); $i++)
   {
      echo $keys[$i] . '  ' . count($keys[$i]) . ' ' . $_POST[$keys[$i]] . "<br>";
   }
?>

Re: HTML select with multiple attribute

Posted: Wed Jan 15, 2014 8:20 pm
by Albert Wiersch
Hi Lou,

I think this answers your question:
http://stackoverflow.com/questions/2407 ... box-in-php

Change name='list' to name='list[]' and then access $_POST['list'] as an array.

Here's my test PHP document:

Code: Select all

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>select test</title>
	<meta name="generator" content="CSE HTML Validator (http://www.htmlvalidator.com/)">
</head>

<body>

<ul>
<?php
 if (isset($_POST['list'])) {
  foreach ($_POST['list'] as $names) {
   print "<li>You selected $names<br/>";
  } 
 } 
?>
</ul>

   <form method="POST">
      <select multiple size='6' name='list[]'>
         <option>One</option>
         <option>Two</option>
         <option selected>Three</option>
         <option>Four</option>
         <option>Five</option>
         <option selected>Six</option>
      </select>
      <input type="hidden" name="other" value="hide">
      <input type="submit">
   </form>
   
</body>
</html>

Re: HTML select with multiple attribute

Posted: Wed Jan 15, 2014 10:44 pm
by Lou
Thanks Albert.

What's that line 'after being explained, great scientific discoveries are intuitively obvious.'
Well maybe not a great discovery...

Thanks again.