Skip to content Skip to sidebar Skip to footer

Refilling Drop Down Menu Selection After Form Submission Validation

I'm working on a sign up/registration form in php that resubmits/retains the users input if everything doesn't validate properly. I've got text box, password input, and radio butto

Solution 1:

You may try this, generate values dynamically

Day:

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

Month:

$months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
echo"<select name='month'>";
for( $i = 0; $i <= 11; $i++ )
{
    $m = $months[$i];
    $selectedMonth = isset($_POST['month']) && $_POST['month'] == $i ? 'selected="selected"' : ''; 
    echo"<option $selectedMonth value=$i>$m</option>";
}
echo"</select>";

Year:

echo"<select name='year'>";
for( $i = 2013; $i >= 1900; $i-- )
{
    $selectedYear = isset($_POST['year']) && $_POST['year'] == $y ? 'selected="selected"' : ''; 
    echo"<option $selectedYear value=$i>$i</option>";
}
echo"</select>";

Demo Normal and Demo Selected

Solution 2:

You are doing in the wrong way.

please make the condition inside the each option like below

<optionvalue="2013"<?phpif(isset($_POST['year']) && $_POST['year']==2013){ echo"selected";}?>>2013</option>

in same manner for month.

Solution 3:

With selects you can't set a value ... instead you have to add a selected attribute to the selection option element.

I usually use a function like this to build out my selects

functionshowSelect($name, $options, $selected, $attr = array()){
    $str = "<select name='".$name.'"';
    foreach($attras$name=>$val){
        $str.= " ".$name."='".$val."'";
    }
    $str.=">";
    foreach($optionsas$k=>$val){
        $str.= "<option value='".$val."'".($val==$selected?" selected='selected'":"").">".$k.'</option>';
    }
    $str.="</select>";
}

$name is the name of the element $options is an array in the form "option_value"=>"option_label" $selected is the value of the selection option $attr is an array of the additional attributes to put on the select element (style id etc.)

For example

$days = array();
for($d = 1; $x<=31; $x++){
     $days[(string)$d] = (string)$d;
}

echo showSelect("formDays", $days, $_POST["formDays"], array("id"=>"formDays"));

Post a Comment for "Refilling Drop Down Menu Selection After Form Submission Validation"