Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get multiselect values from form using Golang?

Tags:

html

forms

go

I have a multiple select input in my form and I'm trying to get the selected values in my handler, but I can't, how can I get those values?

<form action="process" method="post">
    <select id="new_data" name="new_data class="tag-select chzn-done" multiple="" style="display: none;">
    <option value="1">111mm1</option>
    <option value="2">222mm2</option>
    <option value="3">012nx1</option>
    </select>
</form>

My Handler:

func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.FormValue("new_data")) // result-> []
    fmt.Println(r.Form("new_data")) // result-> []
}

The form serialized data with option 1 and 2 selected from JS console:

   >$('#myform').serialize() 
   >"new_data=1&new_data=2"
like image 474
Goku Avatar asked Feb 24 '15 15:02

Goku


1 Answers

You can't/shouldn't use the Request.FormValue() function because that only returns 1 value. Use Request.Form["new_data"] which is a slice of strings containing all the values.
But note that if you don't call r.FormValue(), you have to trigger parsing the form (and populating the Request.Form map) by calling Request.ParseForm() explicitly.

You also have an HTML syntax error: the value of the name attribute is not closed, change it to:

<select id="new_data" name="new_data" class="tag-select chzn-done"
    multiple="" style="display: none;">

Here is a complete app to test that it works (error checks ommited!):

package main

import (
    "fmt"
    "net/http"
)

func myHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        // Form submitted
        r.ParseForm() // Required if you don't call r.FormValue()
        fmt.Println(r.Form["new_data"])
    }
    w.Write([]byte(html))
}

func main() {
    http.HandleFunc("/", myHandler)
    http.ListenAndServe(":9090", nil)
}

const html = `
<html><body>
<form action="process" method="post">
    <select id="new_data" name="new_data" class="tag-select chzn-done" multiple="" >
        <option value="1">111mm1</option>
        <option value="2">222mm2</option>
        <option value="3">012nx1</option>
    </select>
    <input type="Submit" value="Send" />
</form>
</body></html>
`
like image 59
icza Avatar answered Oct 31 '22 20:10

icza