Petr Lozovitskii
Petr Lozovitskii

Reputation: 269

How to get multiple values with the same name from HTML form?

I have a Go Fiber webserver. It produces an HTML form like this:

<form method="post" action="/providers">
    <input type="checkbox" name="state" value="1"><label for="state">Provider1</label>
    
    <input type="checkbox" name="state" value="0"><label for="state">Provider2</label>
    
    <input type="checkbox" name="state" value="1"><label for="state">Provider3</label>
</form>

The documentation says c.FormValue("state") retrieves the first value.

Any ideas about how to retrive all the values (an array of the values)?

Upvotes: 0

Views: 62

Answers (2)

MJepbarov
MJepbarov

Reputation: 137

how about using BodyParser?

if err := c.BodyParser(&fiber.Map{}); err != nil {
    return err
}

// get the form data as map
form := c.Request().PostArgs()

// iterate and append
var stateValues []string
form.VisitAll(func(key, value []byte) {
    if string(key) == "state" {
        stateValues = append(stateValues, string(value))
    }
})

oterwise we can use the multipart form parser

form, err := c.MultipartForm()
if err != nil {
    return err
}

stateValues := form.Value["state"]

Upvotes: 0

Petr Lozovitskii
Petr Lozovitskii

Reputation: 269

Can't find a direct solution, but have solved already. Just added a hidden field with Ids and iterate over them on POST request. Here is the form:

<form action="/providers" method="post">
    <input type="hidden" value="1,8,9,10" name="providerids">

    <input type="checkbox" id="state-1" name="state-1" checked><label for="state">Provider 1</label>
    <input type="checkbox" id="state-8" name="state-8" checked><label for="state">Provider 8</label>
    <input type="checkbox" id="state-9" name="state-9" checked><label for="state">Provider 0</label>
    <input type="checkbox" id="state-11" name="state-10" checked><label for="state">Provider 10</label>
</form>

Here is Go code:

providerIds := c.FormValue("providerids")
Ids := strings.Split(providerIds, `,`)
for _, id := range Ids {
    val[id] = c.FormValue("state-" + id)
}

Not a perfect but works.

Upvotes: 2

Related Questions