Simple drop down pre-set value question

Discussion in 'PHP' started by Alexj17, Aug 20, 2008.

  1. #1
    Hi All

    I am having a little problem with my forms (user fill out).

    I have a form for users to fill out, input boxes, textareas, drop down boxes.

    These values are transferred to php variables which i use to populate other feilds. The user can then re-select the form to make changes. This is ok in some cases and again i can use the varibles to set the value=$variable for the input boxes etc.

    But for the drop down boxes i cant. The html codes uses the

    <select name="cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="fiat" selected="selected">Fiat</option>
    <option value="audi">Audi</option>
    </select>

    Does this mean i have to put and if statement in each options, if variable == xxx then echo the selected code?

    (also i have initally done this, and if no value is selected at all, its picks a answer anyways half way down the list)

    Is this the only way to do this or can my error be solved?

    Regards
    Alex James
     
    Alexj17, Aug 20, 2008 IP
  2. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #2
    Do a switch statement.

    
    $pre_select = ' selected="selected"';
    
    switch ($_POST['cars']) {
    	case "volvo" : $selected['volvo'] = $pre_select;
    		break;
    	case "saab" : $selected['saab'] = $pre_select;
    		break;
    	case "fiat" : $selected['fiat'] = $pre_select;
    		break;
    	case "audi" : $selected['audi'] = $pre_select;
    		break;
    }
    
    echo "<select name=\"cars\">
    <option value=\"volvo\"{$selected['volvo']}>Volvo</option>
    <option value=\"saab\"{$selected['saab']}>Saab</option>
    <option value=\"fiat\"{$selected['fiat']}>Fiat</option>
    <option value=\"audi\"{$selected['audi']}>Audi</option>
    </select>";
    
    PHP:
     
    Kaizoku, Aug 20, 2008 IP
  3. ahowell

    ahowell Peon

    Messages:
    38
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Depending on how many cars he has, that could be a pretty large switch statement. Using a loop will enable you to add/remove cars from the dropdown & processing by adding/removing it from an array.

    <?php
    
    $options = array();
    $dropDownFields = array('volvo', 'saab', 'fiat', 'audi');
    
    foreach ($dropDownFields as $field) {
        $option    = "<option value=\"{$field}\" {selected}>" . ucfirst($field) . "</option>";
        $selected  = (strtolower($_POST['cars']) == strtolower($field)) ? 'selected="selected"' : '';
        $options[] = str_replace('{selected}', $selected, $option);
    }
    
    ?>
    
    <form name="foo">
        <select name="cars">
           <?php echo implode(PHP_EOL, $options); ?>
        </select>
    </form>
    PHP:
     
    ahowell, Aug 20, 2008 IP