PlayKid
PlayKid

Reputation: 871

PHP Posting a combo box value

If I have a combobox like this:

<select name="gender">
<option value="M">Male</option>
<option value="F">Female</option>
 </select>

So when I post using:

$gender = $_POST['gender'];

I will get M or F as the result for $gender, how do I get both M, F and Male,Female?

Upvotes: 0

Views: 1664

Answers (2)

Jordan Wallwork
Jordan Wallwork

Reputation: 3114

Male and Female are simply display values, the actual value that gets posted is either M or F. You can either use a simple

if $_POST['gender'] == "M" { $fullGender = "Male" } else { $fullGender = "Female" }

on the server side, or add a new hidden field to the form and update it when the gender select box changes, ie

$(function() {
    $("[name=gender]").change(function() {
        $("#fullGender").val($(["[name=gender] option:selected").text());
    });
}

(and in the form)

<input type="hidden" name="fullGender" id="fullGender"/>

Upvotes: 1

Prisoner
Prisoner

Reputation: 27618

As JamWaffles has said, there is no easy way to do this.

However, you do have a few options if you must:

  • Option 1 - Use jQuery to post the form for you. You could get the val() ("M"/"F") of the combo box and also the html() value ("Male"/"Female").

  • Option 2 - Set the value to something like value="M|Male" and then use explode() to get each value separately ("M"/"Male").

  • Option 3 - Just use a simple if/else statement on the posted page - if($val == "M") $gender = "Male";

Upvotes: 5

Related Questions