phpformsdrop-down-menuform-processing

How to process select box in PHP when you want to process the actual '<option>' and not the 'value' attribute?


<span> Kamertype :</span>
        <select class="autowidthselect" required area-required="true" name="prijskamertype" onChange="calculatePrice()" id="prijskamertype">
            <option selected="selected" value="">Selecteer kamertype</option>
            <option value="295">Kraaiennest</option>
            <option value="395">Kajuit</option>
            <option value="495">Kapiteinshut</option>
        </select>

When I process the above with the PHP code below, it shows me the content defined in the 'value' attribute, which in this case are the prices. I actually want to show the content defined in the <option> tag (Kraaiennest, Kajuit, Kapiteinshut). How do I achieve that?

(I can not change the values, because of the calculation of the total price at the end of the form)

<?php
$prijskamertype = $_POST ['prijskamertype'];
echo $prijskamertype.' type';
?>

EDIT:

I have created an array and a drop-down list with it:

<?php
$optionskamertype = array();
$optionskamertype[""] = "Selecteer kamertype";
$optionskamertype["295"] = "Kraaiennest";
$optionskamertype["395"] = "Kajuit";
$optionskamertype["495"] = "Kapiteinshut";
?>

HTML-code:

        <span> Kamertype :</span>
        <select class="autowidthselect" required area-required="true" name="prijskamertype" onChange="calculatePrice()" id="prijskamertype">

             <?php
                foreach($optionskamertype as $key => $value)
                {
                    echo '<option value="'. $key .'" label="'. $value .'">'.$value.'</option>';
                }
             ?>

        </select>

What do I have to do now?


Solution

  • This isn't really to do with PHP, it's how HTML forms work: the only thing sent to the server by the browser is the content of the value attribute. (Or, if there isn't one, the content of the option tag, but that doesn't really help here because you still only get one value.)

    What you can do, though, is have an array in your PHP code that has the values and labels of all the options. You can use this to create the drop-down in the first place, and then when the form is submitted do something like this:

    $label = $option_list[ $_POST['whatever'] ];