Forum Moderators: open

Message Too Old, No Replies

Javascript + PHP Select List problem

         

rich0x

9:55 am on Aug 17, 2005 (gmt 0)

10+ Year Member



I've had good look around the internet and have been unable to come up with anything, so I thought I would try here as I've used these forums many a times.

I have a simple form with a javascript function which selects all the elements in the select tags. If I select more than one option from the select the PHP post only returns the last selected value. I've tried adding square brackets to the select name which will post the selected values to PHP but breaks the javascript select all function.

I'm not the worlds greatest javascript coder, all rather a black at to me, so any ideas will be greatly appreciated.

[code]
<?
print_r($_POST);
?>

<form action="<?=$_SERVER['PHP_SELF']?>" name="lookup" method="post">
<select name="s" size="4" multiple>
<option value="one">One
<option value="two">Two
<option value="three">Three
<option value="four">Four
</select>
<input type="button" value="select all" onclick="selAll(true)">
<input type="button" value="select none" onclick="selAll(false)">
<input type="submit">
</form>
<script>
function selAll(_v) {
for(var i=0;i<document.lookup.s.length;i++)
document.lookup.s.options[i].selected=_v;
}
</script>
{/code]

Cheers

Richard

ChadSEO

9:59 pm on Aug 17, 2005 (gmt 0)

10+ Year Member



Richard,

Welcome to WebmasterWorld!

There is actually a bit of a hack to get this to work. I need to append square brackets to the end of the field name, like this:

<select name="s[]" size="4" multiple>

This will make PHP treat it as an Array, and you should be able to loop through all the selected values.

Chad

rich0x

7:31 am on Aug 18, 2005 (gmt 0)

10+ Year Member



Hi Chad,

Thanks for getting back to me so fast, I've tried the adding the square brackets to the name of the select but this breaks the javascript with the following error 'document.lookup.s has no properties'. Not quite sure where to go from here

Cheers

RIchard

RonPK

12:50 pm on Aug 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You really will need the square brackets. You can circumvene the JavaScript problem by not using the name of the select box. Instead, use form.elements[i] :

function selAll(_v) { 
for(var i=0;i<document.lookup.elements[0].length;i++)
document.lookup.elements[0].options[i].selected=_v;

rich0x

7:21 am on Aug 22, 2005 (gmt 0)

10+ Year Member



Many Thanks for that, your a star.

Richard