tags:

views:

44

answers:

2

I know how to 'remember' some form values whenever submitting the form to itself, in this case because of a picture upload function which requires the form to be submitted to itself. I simply want it so that if the user has filled out all fields and then uploads an image, the form doesn't get resetted (cleared).

I have solved this in regular fields and checkboxes like this:

<input type="text" name="headline" id="headline" value="<?php echo @$_POST['headline'];?>">

But how can I do this with drop lists? or radio buttons? There is no value option in a 'SELECT' list, even though I have tried writing in value anyways in the SELECT statement. Didn't work!

So, how can I set the SELECT (drop down lists) value with PHP (OR JAVASCRIPT) ?

If you need more input let me know, thanks!

+2  A: 

For selects, you need to compare each option to your posted value, and handle it individually. Simply print out your options in a loop, and test each value against the value was was previously posted. If it maches, add selected to the attributes of that particular option.

$color = $_POST["colors"];
$colors = array("red","green","blue");

<select name="colors">
<?php foreach ($colors as $option) { ?>
  <option<?php print ($option == $color) ? " selected" : ""; ?>>
    <?php print $option; ?>
  </option>
<?php } ?>
</select>
Jonathan Sampson
+1  A: 

Actually, found out that it is possible to set the selectedIndex with javascript...

So I could put the selectedIndex in a hidden input before submitting the form, and then get that selectedIndex and set it with a javascript function... tricky but suits me better in this case...

  document.getElementById("select").selectedIndex=nr;

Thanks though Jonathan!

Camran
I would go with Jonathan's approach, which is the standard idiom for doing this. Doing it with JS makes your application needlessly JavaScript-dependent and will break the browser's ability to remember the last value you had selected when you go back/forwards.
bobince