Jump to content

Accessing data from PHP and JavaScript from a multiple select Listbox


mweinberger

Recommended Posts

Hi All,

 

I am using a multiple select ListBox form element. I want to be able to access from both PHP and JavaScript. PHP wants the parenthesis in the name, but that conflicts with JavaScript. Here is the code:

 

HTML:

 

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<select name="test[]" multiple="multiple">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
<option value="five">five</option>
</select>
<input type="submit" value="Send" />
</form>

 

PHP

 

<?php
$test=$_POST['test'];
if ($test){
 foreach ($test as $t){echo 'You selected ',$t,'<br />';}
}
?>

 

JavaScript

 

var objListBox, Methods, iIndex;

objListBox = document.getElementById("test");
for (Methods = "", iIndex = 0; iIndex < objListBox.options.length; iIndex++)
if (objListBox.options[iIndex].selected)
{
if ("" == DonateMethods)
	Methods = objListBox.options[iIndex].value;
else
	Methods += "," + objListBox.options[iIndex].value;
}

 

If I take out the parenthesis from the HTML definition, then JavaScript is happy but PHP is not. If I leave the parenthesis in, then PHP is happy and JavaScript is not. How do I make BOTH PHP and JavaScript happy?

 

Thanks in advance,

 

Marci

  • 5 years later...

For those needing a solution for this problem (it took me 3 hours to figure it out):

 

Step 1) add id tag to the select tag:

 

<select name='eras[]' id='eras_id' multiple>

 

Step 2) in your Javascript use the getElementByID function to grab the object handle:

 

objListBox = document.getElementById('eras_id');

for (var i = 0; i < objListBox.options.length; i++) {

if (objListBox.options.selected) {

alert('Found selected option ' + i + ', with value '+ objListBox.options.value);

}

}

 

step 3) Get a cold Heineken out of the fridge to celebrate victory :tease-01: !

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.