Passing hidden input fields in HTML Select option

Andy Birchall picture Andy Birchall · Jul 23, 2009 · Viewed 72k times · Source

Does anyone know if it's possible to pass a hidden request parameter in with a <select> <option> element in a HTML form?

So for example, if the user selected <option value="foo">foo</option> from a <select> list of options, could I somehow pass a hidden value in, as well as the "foo" value, and retrieve that as a request parameter? E.g. <input type="hidden" name="x" value="bar"/> would enable me to get the values "foo" and "bar" from the request when the user selected the foo option.

Thanks

Answer

Jeff Widmer picture Jeff Widmer · Jul 23, 2009

A select list has both a value that is displayed to the user and a value that is passed back to the server in the form post. So you could use some sort of delimiter in the posted value to get both values sent back and then parse them at that point:

        <select id="myselectlist" >
            <option value="foo|bar">foo</option>
            <option value="foo2|bar2">foo2</option>
        </select>

But better yet would be to pass back an ID value which you could then use to know which item was selected from a database and also use it to look up the second related item:

        <select id="myselectlist" >
            <option value="123">foo</option>
            <option value="124">foo2</option>
        </select>

Your database might look like this:

ID   DisplayValue   OtherData   
123  foo            bar     
124  foo2           bar2