Bind HTML checkboxes

  1. package main
  2. import "github.com/kataras/iris/v12"
  3. func main() {
  4. app := iris.New()
  5. app.RegisterView(iris.HTML("./templates", ".html"))
  6. app.Get("/", showForm)
  7. app.Post("/", handleForm)
  8. app.Listen(":8080")
  9. }
  10. func showForm(ctx iris.Context) {
  11. ctx.View("form.html")
  12. }
  13. type formExample struct {
  14. Colors []string `form:"colors[]"` // or just "colors".
  15. }
  16. func handleForm(ctx iris.Context) {
  17. var form formExample
  18. err := ctx.ReadForm(&form)
  19. if err != nil {
  20. ctx.StopWithError(iris.StatusBadRequest, err)
  21. return
  22. }
  23. ctx.JSON(iris.Map{"Colors": form.Colors})
  24. }

templates/form.html

  1. <form action="/" method="POST">
  2. <p>Check one or more colors</p>
  3. <label for="red">Red</label>
  4. <!-- name can be "colors" too -->
  5. <input type="checkbox" name="colors[]" value="red" id="red">
  6. <label for="green">Green</label>
  7. <input type="checkbox" name="colors[]" value="green" id="green">
  8. <label for="blue">Blue</label>
  9. <input type="checkbox" name="colors[]" value="blue" id="blue">
  10. <input type="submit">
  11. </form>

Response

  1. {
  2. "Colors": [
  3. "red",
  4. "green",
  5. "blue"
  6. ]
  7. }