S
SolidJS12mo ago
Grahf

Only able to get one value from multiple checkboxes that are checked

In my form, I'm only able to get the value of one checkbox that's checked, even if I check multiple check boxes. I have a form setup that successfully gets values from inputs. Some of the inputs are checkboxex that I make like this:
<fieldset>
<legend>Choose Stuff to Search</legend>
<For each={signal()} fallback={<div>Loading Stuff...</div>}>
{(item) => (
<div>
<input
type='checkbox'
id={item}
name='check-select'
value={item}
/>
<label for={item}>{item}</label>
</div>
)}
</For>
</fieldset>
<fieldset>
<legend>Choose Stuff to Search</legend>
<For each={signal()} fallback={<div>Loading Stuff...</div>}>
{(item) => (
<div>
<input
type='checkbox'
id={item}
name='check-select'
value={item}
/>
<label for={item}>{item}</label>
</div>
)}
</For>
</fieldset>
And that makes a bunch of check boxes I can check/uncheck.
In my form I can only seem to get the value of one of the checkboxes.

const [submitting, { Form }] = createServerAction$(async (form) => {

const selections = form.get('check-select')

console.log('what is this?: ', form.get('check-select'))

return await getSearch(selections)
})

const [submitting, { Form }] = createServerAction$(async (form) => {

const selections = form.get('check-select')

console.log('what is this?: ', form.get('check-select'))

return await getSearch(selections)
})
I was expecting an object or array to come back but I'm just getting a string from the form.get('check-select') Do I need to give each checkbox a unique name and do a form.get for each checkbox?
6 Replies
REEEEE
REEEEE12mo ago
Afaik, each checkbox needs to have a unique name
Grahf
Grahf12mo ago
I ended up doing this: const [submitting, { Form }] = createServerAction$(async (form) => { const searchString = form.get('search') const entries = form.entries() const selected = [] for (const [name, value] of entries) { if (name === 'check-select') { selected.push(value) } } return await getSearch(searchString, selected) })
Erik Demaine
Erik Demaine12mo ago
You might have more luck setting name={item} (or omitting it; id should suffice)
Grahf
Grahf12mo ago
The mozilla docs use the same name for multiple inputs.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/checkbox under "Handling multiple checkboxes" I also don't know how I would get which check boxes the user selected if I just used ids. Unless I made an array of all the ids and did the exact same thing I did in the code above, just with ids
Erik Demaine
Erik Demaine12mo ago
Ah, I didn't realize that. Your solution seems good then!
Grahf
Grahf12mo ago
thanks for the support. I'm just a simple man trying to build a simple website