Hi,

Just started picking up on PHP (from asp)... Going well. Like php a lot... except for........ My code is below... if someone can please help me get ALL the data from the $POST["catlist"] I would appreciate it.

Firstly: To ensure all the contents of "catlist" are selected, chuck this into the top.

<SCRIPT LANGUAGE=JavaScript>
    function selectAll(box) {
        for(var i=0; i<box.length; i++) {
            box.options[i].selected = true;
        }
    }
</SCRIPT>

Secondly: The form

<form action="this.php" method="post" name=form>
select multiple size="10" name="catlist'>
<option value="3">Painter</option>
<option value="1">Database Designers</option>
<option value="2">Volunteer</option>
</select>
<input type="submit" name="btnSubmit" value="Submit" onClick="selectAll(this.form.catlist);">
</form>

Thirdly: this.php to capture the list into an array like this:

$catarray[0]=3
$catarray[1]=1
$catarray[2]=2

Here is what I have tried: (using php5)

$catarray= ($_POST['catlist']);
$catarray= array($_POST['catlist']);

other variations.

The most confusing is that Count($_POST['catlist']);)=1

Please please help... sob... boo hooo... sob..
My brain hurts....

J-E

Edited 3 Years Ago by pyTony: fixed formating

$catarray= $_POST['catlist'];

shouldn't need parenthesis.

Have you tried:

print_r($catarray);

I haven't pulled arrays from POST yet, so I'm not sure how it works. Here is a small script to output all the variables that are defined in php. You will be interested in the _POST section :)

$output = get_defined_vars();
$fh = fopen('output.txt', at);
foreach($output as $yek => $out)
{
      fwrite($fh, "*******************$yek****************************\r\n\r\n");
      foreach($out as $key => $o)
      {
            fwrite($fh, "$key\t\t\t\t");
            fwrite($fh, $o);
            fwrite($fh, "\r\n\r\n");
      }
}
fclose($fh);

That way you can be sure what the data looks like and if it is indeed being transeferred from the html form.

Dance

Thanks for that... Unfortunately it seems there is no array coming through the POST. Only one value instead of 3.... any suggestions on how to get around it?

I will play around further.

J-E

Found this example of an html form. Hope it helps.

<form action="handle_event.php" method="post">
<p> Event name: <input type="text" name="name" size="30" /></p>

<p>Week Days:
<input type="checkbox" name="weekdays[]" value="Sunday" />S
<input type="checkbox" name="weekdays[]" value="Monday" />M
<input type="checkbox" name="weekdays[]" value="Tuesday" />T
<input type="checkbox" name="weekdays[]" value="Wednesday" />W
<input type="checkbox" name="weekdays[]" value="Thursday" />T
<input type="checkbox" name="weekdays[]" value="Friday" />F
<input type="checkbox" name="weekdays[]" value="Saturday" />S
</p>

<input type="submit" name="submit" value="Add the Event!" />
</form>

It's from "PHP for the World Wide Web" by Larry Ullman http://www.dmcinsights.com/phpvqs2/

Dance

Thanks a million. I appreciate your time. The solution makes perfect sense. Makes me wanna take up line dancing (sometimes).

Cheers

J-E

Sideline comment No big deal.. it did break the "selectALL()" javascript (see point 1 of original post). But that should be a minor issue to fix.

Yeah I just posted the example, didn't try to make it work for your situation, please excuse my laziness :mrgreen:

On a ranting note: I see the need for javascript, but HATE how PICKY it is.......

Dance

While that solution is cute, it is a workaround, and not a solution. I'm having the same issue, but my selections must be read from a DB; they are not static so defining checkboxes will not do.

Does anybody have a real solution to this problem?

Thanks!
Karim Varela
<URL SNIPPED>

<disclaimer>Just took a look at this post again, and I'm not entirely sure that a multiple select won't post as a CSV value by default, so that's worth a go, but if you want to get down and dirty with some javascript, read on...</disclaimer>

Sure. You want to pass the selected values as a comma separated string. For the checkboxes, it's easy because the array is build for you and PHP reads it in no problem.

With the multiple selection SELECT element, you're going to have to make your javascript work a little harder.

Below, I have a function I wrote to parse a form for values. I use this to pass to an ajax call, but you could use it in a normal form submit as well, you would just have to read the parsed values from your multiple select into a hidden element.

But first the part you're interested in:

var sels = form.getElementsByTagName('select'); // parse select elements
	for(var i=0;i<sels.length;i++)
	{
		q += '&' + sels[i].name + '='
		for (var j=0; j<sels[i].options.length; j++)
			if (sels[i].options[j].selected)
				q += escape(sels[i].options[j].value)+',';
	}

This is building a query string to pass in a GET, but you can easily modify it to build a CSV string.

Full function:

function saveForm(form)
{
	var q = (form.id ? '?key='+form.key.value : '?key='); //key is the primary key in the db
	var els = form.getElementsByTagName('input');
	for(var i=0;i<els.length;i++) //parse input elements
	{
		if(els[i].type=='checkbox')
			q += '&' + els[i].name + '=' + (els[i].checked==true ? els[i].value : '0');
		else
			q += '&' + els[i].name + '=' + escape(els[i].value);
	}
	var tels = form.getElementsByTagName('textarea'); //parse textarea elemtns
	for(var i=0;i<tels.length;i++)
	{
			q += '&' + tels[i].name + '=' + escape(tels[i].value);
	}
	
	var sels = form.getElementsByTagName('select'); // parse select elements
	for(var i=0;i<sels.length;i++)
	{
		q += '&' + sels[i].name + '='
		for (var j=0; j<sels[i].options.length; j++)
			if (sels[i].options[j].selected)
				q += escape(sels[i].options[j].value)+',';
	}
	
        sndReq('common/saveInd.php'+q,'sd'+form.count.value); // this would be a call to an ajax request
}

I know this thread is old, but I feel it deserves this bump as I have the solution, which has not been given previously in this thread. Moreover this thread ranks well in search search, so I think the solution will benefit.

No need of any javascript hassles, instead use an array name for the 'select' field.

<select name="choices[]" multiple="multiple">
<option value="b">bold</option>
<option value="i">italic</option>
<option value="u">underline</option>
<option value="s">strike</option>
</select>

retreive it through(depending upoin GET/POST)

$multiple_choices=$_POST['choices'];

I know this thread is old, but I feel it deserves this bump as I have the solution, which has not been given previously in this thread. Moreover this thread ranks well in search search, so I think the solution will benefit.

No need of any javascript hassles, instead use an array name for the 'select' field.

<select name="choices[]" multiple="multiple">
<option value="b">bold</option>
<option value="i">italic</option>
<option value="u">underline</option>
<option value="s">strike</option>
</select>

retreive it through(depending upoin GET/POST)

$multiple_choices=$_POST['choices'];

@rohan_shenoy...

I agree to Rohan....

This is by-far the best solution for multiple selection... Just put it as an array.. And it will solve your problem...

I will elaborate more on this by giving u as an example... Once you take the select name as an array... on submitting the form, PHP takes it also as an array..

So,
$_POST is also an array..

Modifying above example...

<?php
$my_choices = $_POST['choices'];
echo "My total selected choices are ".count($my_choices);

//This will print the count of the array

$i=0;
for($i < count($my_choices))
{
    echo $my_choices[$i]." , ";
}

//Now you can use this array - $my_choices in any way you want
?>

Thanks for this solution rohan_shenoy!
was looking for something like this, without the noobish and slow javascript solution.

You made my day!

Thx, VâRûN & rohan
I came to this with a different query:
yes the solution for a single select is name="choices[]" etc. But what about when you have a more than one?
To clarify:
If I have a multiple data entry table, arrays for each input field works nicely, so eg
id[], name[], age[], etc will each return an array which can be parsed to give me a data set for each "person". Our choice[], however, runs into problems as I get one combined array rather than an array for each "person".
The only solution I see is to create a unique name for each, thus:
choice_0[]
choice_1[]
choice_2[], etc then parse the _POST var names to build my datasets.
Anyone got any better ideas?
Thx in advance!

@rohan_shenoy and anyone else reading this thread or new posts to the forum,

FABulous answer and almost solves my problem. Thing is, after I've done the
<select name="choices[]" multiple="multiple">...</select>
and
$myChoices = $_POST;
when I then use $myChoices in a foreach statement like this:
foreach ($myChoices as $thisone) {
$emailBody .= "$thisone, " ;
}
I'm getting an error message saying
Invalid argument supplied for foreach() in...
The weird thing is, it works! That is, the code collects the selected items from the <select> options and puts them into $emailBody and then sends the message to me. However, I'm getting this error message at the top of my page! Not what my client wants to see!

Any suggestions for getting rid of the error message?

Thanks!

Nevermind! I figured it out.

When the page first loads, $interests is empty because there's no information yet from $_POST! So I put it inside an if() that checked to see if the form was submitted. Now works like a charm. YAY!!

Remember, you're posting an array so therefor the name="" needs to be an array name, like selectOptions[]

i.e.
<select name="selectOptions[]" multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
</select>

<?php
$my_choices = $_POST['choices'];
    foreach ($my_choices as $value)
   {
   echo $value . ",";
   }
?>

Here's what worked for me - hopefully this helps someone ;)

This article has been dead for over six months. Start a new discussion instead.