Jump to content

remaining value for select :(


asmith

Recommended Posts

<form action="$_SERVER['PHP_SELF'] method="post">
<input type="text" name="hello" value="$_POST['hello'] />
<input type="submit" value="test" />
</form>

the above code , by pressing test (submit) button reload the page, and if user had typed anything to the field, it remains.

 

i can't do the same thing with select option : (and more important to me, multiple select options)

 

 

<form action="$_SERVER['PHP_SELF'] method="post">
<select name="test" >
<option value="1"> 1 </option>
<option value="1"> 2 </option>
<option value="1"> 3 </option>
</select>
<input type="submit" value="test" />
</form>

 

 

the best thing i could do was :

 


<form action="$_SERVER['PHP_SELF'] method="post">
<select name="test" >
<option value="$_POST[test]"> $_POST[test] <option>
<option value="1"> 1 </option>
<option value="1"> 2 </option>
<option value="1"> 3 </option>
</select>
<input type="submit" value="test" />
</form>

 

this code , when the page reload , saves the users choice, but if the user click on the menu , he will saw his selected option 2 times!

the problem gets bigger, when i have about 20 options , that they can be choose multiple.

anyone help ?

 

Link to comment
https://forums.phpfreaks.com/topic/79290-remaining-value-for-select/
Share on other sites

Put each select option into an array:

 

<?php
$options = array (
"1"  =>  "Im 1",
"2"  =>  "Im 2",
"3"  =>  "Im 3"
);
?>

 

Then, when displaying the select, do this:

 

<?php
echo "<select name='test'>"; // start the dropdown menu

while ( list($id,$name) = each($options) ) // for each option in the array
{
  $sel = ""; // keep blank by default

  if (isset($_POST['select']) AND $_POST['select'] == $id) // if the post-select option is available, check if it's ours
  {
    $sel = "selected"; // makes it selected
  }

  echo "<option id={$id} {$sel}>{$name}</option>"; // show the option
}
echo "</select>"; //all done
?>

^ It sets the value and title (whats shown) for each select's option, otherwise it wont know how many options to create. You can set it to whatever you want, like..

 

"Post1" => "asmith",

"Post2" => "Wes1890",

"Smith" => "asmith",

"Wes" => "Wes1890",

 

 

whatever you want

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.