Jump to content

How to "remember" select tag value--please help


geekisthenewsexy

Recommended Posts

Hi guys,i was trying to figure out how to work with <select> tag, remember/set the value that was being selected before. The values are fetched from the database..From other forums I've been, they said that $_SESSION will do the work but I'm having trouble where to put it inside my code.. Please take a look at this

 

<form name="form1" action="do_set.php">
<?php
   $sql="SELECT school_year FROM admin_sy ORDER BY school_year ASC" or die (mysql_error());
   $result=mysql_query($sql);
   echo "Set schoolyear: <select name=SY value=''>";
   while($row=mysql_fetch_array($result)) {
        echo "<option value=$row[school_year]>$row[school_year]</option>";
        }
        echo "</select>";
        ?>
        <br>
        Sem: <select name="sem">
        <option value="1st">1st</option>
        <option value="2nd">2nd</option>
        <option value="Summer">Summer</option>
      </select>
     <input type="Submit" name="submit" value="Set">
     </form>

 

as you can see,  'school_year' are fetched from a database.

now my problem is, when i select a specific year, the value should be "remembered" after i click set or refresh the page or go back from the previous page. this will be useful so the user will be able to know what school year has already been set.

hope you guys can help.. :-\ thanks in advance.

Here is a small snippet:

 

<option value = "user" <?php if ($row->role == "user") echo "selected"; ?>>User</option>

<option value = "staff" <?php if ($row->role == "staff") echo "selected"; ?>>Staff</option>

<option value = "admin" <?php if ($row->role == "admin") echo "selected"; ?>>Admin</option>

When it comes to this kind of thing, I always create a function that does the comparison for me to avoid having an if statement in the code... just gets messy.

 

 

<?php

function compare($currentValue, $compareTo){
    if($currentValue == $compareTo){
        echo 'selected="selected"'; 
   }
}
?>

Then to steal from revraz... (thanks buddy) :)

 

<option value = "user" <?php compare($row->role, 'user'); ?>>User</option>
<option value = "staff" <?php compare ($row->role, 'staff'); ?>>Staff</option>
<option value = "admin" <?php compare($row->role, 'admin'); ?>>Admin</option>

 

p.s. I don't think compare is a reserved word, but I typically would not use that as a function name. Mine are usually called something like selectEdit (as this is typically used when re-populating a form for editing... or when re-populating because of errors.

 

Nate

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.