Jump to content

Make selection list sticky


illadelphiakid

Recommended Posts

I'm trying to get this drop down menu to be sticky once the user clicks submit. 

 

Here's my entry code:

if (isset($_POST['guess']))
{
    if ($_POST['guess'] == $_SESSION['number'])
    {
        $response = "You Win!";
        unset($_SESSION['number']);
    }
    else
    {
        $_SESSION['tries']++;
        
        if ($_SESSION['tries'] < 3)
        {
            $response = "Try #{$_SESSION['tries']}<br /><br />";
        }
        else
        {
            $response = "You Lose";
            unset($_SESSION['number']);
        }
    }
}

if (empty($_SESSION['number']))
{
    $_SESSION['tries'] = 0;
    $_SESSION['number'] = rand(1, 10);
}

 

And in my body:

 

 <select name="guess" id="guess">
                <?php
                
                for ($i = 1; $i < 11; $i++)
                {
                    echo "<option value='{$i}'>{$i}</option>";
                }
                
                ?>
            </select>

Link to comment
https://forums.phpfreaks.com/topic/249071-make-selection-list-sticky/
Share on other sites

Should work.

 

<select name="guess" id="guess">
    <?php
    
    for ($i = 1; $i < 11; $i++)
    {
        $selected = (isset($_POST['guess']) && $_POST['guess'] == $i) ? 'selected="selected"' : '';
        echo "<option value='{$i}' {$selected}>{$i}</option>";
    }

    ?>
</select>

 

In the future, you should really try to do your work on your own.  That was meant to be an example so you could write your own.

That's the same process I typically use. However. in the interest of efficiency I would not do the isset() test on each iteration of the loop. Just do it once before the loop and set a variable to test against.

 

    $selected_guess = (isset($_POST['guess'])) ? : $_POST['guess'] : false;
    for ($i = 1; $i < 11; $i++)
    {
        $selected = ($selected_guess === $i) ? 'selected="selected"' : '';
        echo "<option value='{$i}' {$selected}>{$i}</option>";
    }

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.