dongyisa6254 2015-12-05 18:03
浏览 261
已采纳

通过ParseForm()检索表单选项ID

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>
</select>

And this in my Go file:

func filmFunc(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    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"))
        }
    
        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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作