How to select a select value and maintain after Submit with PHP

Asked

Viewed 1,160 times

0

I have the following code that when selecting a month, it puts in the variable $mes, the selected value:

if (isset($_POST['mes']))
{
    $mes = $_POST['mes'];
    echo "$mes";
}

(isset($_POST["mes"])) ? $mes1 = $_POST["mes"] : $mes1=3;
echo '
<form method="post" action="" name="form">  
 <select name="mes" id="mes">
    <option value="1">Janeiro</option>
    <option value="2">Fevereiro</option>
    <option value="3">Março</option>
    <option value="4">Abril</option>
    <option value="5">Maio</option>
    <option value="6">Junho</option>
    <option value="7">Julho</option>
    <option value="8">Agosto</option>
    <option value="9">Setembro</option>
    <option value="10">Outubro</option>
    <option value="11">Novembro</option>
    <option value="12">Dezembro</option>
 </select>
 <input name="submit" type="submit">
</form>
';

But after selecting and functioning, the select field goes back to the first value, in the case January.

How do I, after selecting and giving ok, select the field to be selected the value $mes?

1 answer

1


A solution would be to put the months in an array and make a loop. After giving the submit on the page check the selected month is equal to the current item of the loop and do the selected:

<?php

$meses = array(1=>'Janeiro', 2=>'Fevereiro', 3=>'Março', 4=>'Abril', 5=>'Maio', 6=>'Junho', 7=>'Julho', 8=>'Agosto', 9=>'Setembro', 10=>'Outubro', 11=>'Novembro', 12=>'Dezembro');

if (isset($_POST['mes']))
{
    $mes = $_POST['mes'];
    echo "$mes";
}
?>
<form method="post" action="" name="form">  
 <select name="mes" id="mes">
    <?php
    foreach($meses as $n=>$m){

        $selected = (isset($_POST['mes']) && $_POST['mes'] == $n) ? 'selected' : '';

        echo '<option value="'.$n.'" '.$selected.'>'.$m.'</option>';
    }
    ?>
 </select>
 <input name="submit" type="submit">
</form>
  • worked perfect! Thank you!!!

  • Taking advantage (forgot to put) in case of input how would be? I have an input field that is the year <input type="number" id="year" name="year" value="2017" style="width:100px;"></input>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.