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
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.

Link to comment
Share on other sites

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>";
    }

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.