Janek Sławiński Janek Sławiński - 7 months ago 11
PHP Question

HTML/PHP select form having value selected before

I have prepared a simple .php document that allows user to pick a value to be printed and then posts it to php script that prints it. Here is the code i used:

<?php
echo('<form method="post">
Select value:
<select type="integer" name="val" value= "">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<input type="submit" name="submit" value="display"/>
</form>');
$val = $_POST['val'];
echo($val);
?>


however, I have two problems with it:


  1. When first opened it displays a naughty line "Notice: Undefined index: val in C:\ ...\test.php on line 12". How do I fix it?

  2. When I press display button, printing script works fine, but list value comes back to 1 instead of the number selected.



This is my first post on StackOverflow, sorry if I broke any rules, I just couldn't find the solution.
Thanks in advance for any advice!

Answer

Firstly, <select> does not have a type="integer" (it doesn't even exist), nor does it have a "type" to begin with, so we'll just remove that.

<form method="post">
            Select value:
            <select name="val">
            <option value="1" <?php if(isset($_POST['val']) && $_POST['val'] == 1){ echo "selected";}?>>1</option><!-- check the posted value and compare it with option value and if equal then add selected attribute-->
            <option value="2" <?php if(isset($_POST['val']) && $_POST['val'] == 2){ echo "selected";}?>>2</option>
            <option value="3" <?php if(isset($_POST['val']) && $_POST['val'] == 3){ echo "selected";}?>>3</option>
            <option value="4" <?php if(isset($_POST['val']) && $_POST['val'] == 4){ echo "selected";}?>>4</option>
            <input type="submit" name="submit" value="display"/>
            </form>

<?php
    if(isset($_POST['val'])){ // check value is posted and set or not
        $val = $_POST['val'];
        echo($val);
    }
?>

Or more better:-

<form method="post">
    Select value:
    <select name="val">
    <?php 
    for($i =1;$i<=4;$i++){ // start loop
        if(isset($_POST['val']) && $_POST['val'] == $i){ // check posted value is set and equal to option or not if yes then add selected.
            echo "<option value=$i selected>$i</option>";
        }else{
            echo "<option value=$i >$i</option>";
        }
    }
    ?>
    </select>
    <input type="submit" name="submit" value="display"/>
</form>         
<?php
    if(isset($_POST['val'])){ // check posted value is set or not
        $val = $_POST['val'];
        echo($val);
    }
?>

Note:- file extension must be .php.

Comments