That is not how HTML <form>
works. When you use a <select>
in a <form>
, you have to specify the name
attribute at the <select>
- you did this right. And you have to specify the value
attribute for the <option>
tags, not the id
. You may specify the id
attribute too (e.g. if you want to refer to the tag by its id), but that is not what gets sent when the form is submitted.
When the form is submitted, a "key"="value"
pair will be sent for the <select>
, where "key"
will be the value of the name
attribute of <select>
, and "value"
will be the value of the value
attribute of the <option>
that is selected.
And you can get the value of a submitted form field by its name using Request.FormValue()
, note that this also calls Request.Parseform()
if necessary so you can even omit that call.
See this working example:
func formHandler(w http.ResponseWriter, r *http.Request) {
if selectedFilm := r.FormValue("film"); selectedFilm != "" {
log.Println("Selected film:", r.FormValue("film"))
}
w.Write([]byte(html))
}
func main() {
http.HandleFunc("/", formHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
const html = `<html><body>
<form method="POST" action="/">
<select name="film" id="films">
<option value="1">The Godfather</option>
<option value="2">The Godfather: Part II</option>
</select>
<input type="submit" value="Submit">
</form>
</body></html>`
When you select "The Godfather"
and submit, the console shows:
2015/12/05 21:18:42 Selected film: 1
When you select "The Godfather: Part II"
and submit, the console shows:
2015/12/05 21:18:45 Selected film: 2