2015-12-05 18:03
浏览 220


I am trying to get the option value id from HTML form dropdown.

Let's say I have these lines in my HTML file:

<select name="film" id="films">
<option id="1">Godfather</option>

And this in my Go file:

func filmFunc(w http.ResponseWriter, r *http.Request) {
    film_raw := r.Form["film"]
    film := film_raw[0]

This will give me the text from the option ("Godfather"), but I need to get the option id ("1") and save it as a variable. How can I do it?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtgu21994537 2015-12-05 20:19

    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"))
    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>
        <input type="submit" value="Submit">

    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
    点赞 评论

相关推荐 更多相似问题