This is my HTML :
<input type="checkbox" name="product_image_id" value="0" />
<input type="checkbox" name="product_image_id" value="1" />
<input type="checkbox" name="product_image_id" value="2" />
If I check all the options and I use r.FormValue("product_image_id")
to get the value of checked options, I will only get the value 0
.
I mean I can only get the first value, and I can't get other value although it was checked.
Please help me. Thanks.
Request.FormValue
only returns the first value if there is more than one. From the Documentation:
FormValue returns the first value for the named component of the query.
...
To access multiple values of the same key, call
ParseForm
and then inspectRequest.Form
directly.
r.FormValue
returns the first value from the list of options instead use r.Form
, this returns a list. you can access your values by r.Form["product_image_id"]
HTML
<form method="post" name="myform" action="http://localhost:8081/post" >
<input type="checkbox" name="product_image_id" value="Apple" />
<input type="checkbox" name="product_image_id" value="Orange" />
<input type="checkbox" name="product_image_id" value="Grape" />
<input type="submit">
</form>
Go
// ProcessCheckboxes will process checkboxes
func ProcessCheckboxes(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Printf("%+v
", r.Form)
productsSelected := r.Form["product_image_id"]
log.Println(contains(productsSelected, "Grape"))
}
func contains(slice []string, item string) bool {
set := make(map[string]struct{}, len(slice))
for _, s := range slice {
set[s] = struct{}{}
}
_, ok := set[item]
return ok
}
Output
Orange and Grape checboxes are checked and submitted
map[product_image_id:[Orange Grape]]
2016/10/27 16:16:06 true
Apple and Orange checboxes are checked and submitted
map[product_image_id:[Apple Orange]]
2016/10/27 16:17:21 false
HTML
<input type="checkbox" name="product_image_id" value="0" />
<input type="checkbox" name="product_image_id" value="1" checked/>
<input type="checkbox" name="product_image_id" value="2" checked/>
<input type="checkbox" name="product_image_id" value="3" />
<input type="checkbox" name="product_image_id" value="4" checked/>
GO
r.Form["product_image_id"][0] == "1"
r.Form["product_image_id"][1] == "2"
r.Form["product_image_id"][2] == "4"
It will be working.
Am I late?