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

Link to comment
Share on other sites

  • 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: !

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.