Closed
Description
Hey I have the following code:
<input type="checkbox" name="colors" value="red">Red
<input type="checkbox" name="colors" value="green">Green
<input type="checkbox" name="colors" value="blue">Blue
<input type="checkbox" name="colors" value="black">Black
<input type="checkbox" name="colors" value="white">White
What is the correct way to bind them (using Bind Middleware) to obtain all data from them? I'm binding to an string but I only get the first one, if I bind to a slice I get an error.
Any ideas? Does Bind support this?
This is done in other languages by naming the group as an array:
<input type="checkbox" name="colors[]" value="purple">Purple
Then my struct will have a slice to bind. But I can't seem to make it work here.
Activity
techjanitor commentedon Oct 2, 2014
Hmm I haven't tested it, but in Gorilla that would work like this:
and the form would look like this:
phrozen commentedon Oct 2, 2014
I'm reading the code on Binding and AFAIK is not supported. Apparently slices are supported but not the way checkboxes work, just with json or xml body. Maybe I will start using Gorilla for that.
EtienneR commentedon Jun 4, 2015
Use this HTML syntax :
In your Go structure, defined a string array for your checkboxes :
Your result will be an array like this :
manucorporat commentedon Jun 4, 2015
@EtienneR does that really works? it would be interesting to add a unit test for that!
EtienneR commentedon Jul 23, 2015
Yes, it's works for me (with the v1.0rc2 of Gin) :
In the main.go :
And the form ("views/form.html") :
If we check all colors, the result is like :
mh-cbon commentedon Aug 24, 2016
@manucorporat anyways to update the binding section of the doc ? EtienneR's solution works for me too.
docs(readme): add binding html checkbox example, close #129
docs(readme): add binding html checkbox example, close #129 (#994)
docs(readme): add binding html checkbox example, close gin-gonic#129 (g…
croatiangrn commentedon Jul 9, 2018
Is there a way to bind a slice of structs like this using formData in JS?