View Full Version : Multiple values in one listbox to a textbox

06-22-2004, 11:57 AM
Hi, I have a form which has a listbox and a textbox. I named the listbox as fruit[] as I want to select multiple values in it rather than one. When I control-click on the listbox to select multiple values, I wish to show what I have selected in the listbox to the textbox on the same form...something like:

banana, pineapple, watermelon, strawberry....

I am able to show this in PHP (but not into the textbox, just echo only)...the code is like this:

if (isset($_POST[Submit])) {
$Fruit = $_POST['Fruit'];

foreach ($Fruit as $Fruit1) {

$Fruit1 = $Fruit1 . "," . " ";
echo "$Fruit1\n";


I am not good in array kind of thing, somemore in Javascript. Hope someone can help me on this, thanks!

06-22-2004, 02:08 PM
Like this?

<script type="text/javascript">
function showData(sel){
var str='';
for (var i=0;i<sel.options.length;i++){
if (sel.options[i].selected){
str=(str!='') ? ', '+sel.options[i].value : sel.options[i].value;
sel.form.selectedFruits.value = str;
<select name="fruit[]" size="5" multiple="multiple" onchange="showData(this)">
<option value="banana">banana</option>
<option value="pineapple">pineapple</option>
<option value="watermelon">watermelon</option>
<input type="text" name="selectedFruits" />

06-23-2004, 03:32 AM
Thanks mate, I think it is close...

Testing shows that if you select banana and pineapple for instance, it shows only .pineapple rather than banana, pineapple.

I wonder where the dot comes from...so I look at this line of code:

str=(str!='') ? ', '+sel.options[i].value : sel.options[i].value;

Not too sure what it does, but I will keep trying (to debug). :)

06-23-2004, 04:03 AM
You might be mistaking comma to be a dot or you have a dot in the option value?

In any case, I saw where the error is. I forgot the + operator.

str+=(str!='') ? ', '+sel.options[i].value : sel.options[i].value;

06-23-2004, 04:25 AM
Thanks very much! Now it works! :thumbsup:

I am also puzzled by that dot, I am sure it is a comma in your line of code...this shows the beauty of programming :D