Search code examples
perldrop-down-menucgi

Obtaining the text, not the value, from a select element with Perl CGI?


Given an HTML form:

<select name="fruit">
<option value="1">Apple</option>
<option value="2">Banana</option>
</select>

Suppose the user chooses the second option and submits the form. In a Perl CGI application, I can get the chosen value, 2, by calling param('fruit'). How do I get the chosen label, Banana?

I've been searching the web for an hour and can't find the answer.


Solution

  • That's not possible. That information is not transmitted. The browser only puts fruit=1 into the HTTP request it creates. There is no way for your Perl program to have this information. It's simply not there.

    Typically the Perl program would control what value means what in a situation like that. You would have a matching set up in your program that knows that 1 is Apple and 2 is Banana.

    You have to change the value attributes. Maybe to something like 1|Banana, to retain the 1 in case it is needed somewhere else. The pipe | in that case is arbitrary and I just picked it because your data does not seem to contain such a character.

    If you cannot control the page, you could also make your Perl program fetch the same page that contains the form and parse it, to look up what the 1 means. That sounds very inefficient though. Look into HTML::TreeBuilder for a standard way of parsing HTML.