Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doesn't seem to work with multi-selects #10

Closed
cullylarson opened this issue Feb 21, 2018 · 2 comments
Closed

Doesn't seem to work with multi-selects #10

cullylarson opened this issue Feb 21, 2018 · 2 comments

Comments

@cullylarson
Copy link

Using a <select multiple='multiple'>. When more than one value is selected, form-to-object only includes one of the selected values, not all of them.

This reproduces the error:

Javascript

const formToObj = require('form-to-object')
const formEl = document.querySelector('#theForm')
const params = formToObj(formEl)
console.log(params)

HTML

<form id='theForm' action='' method='post'>
  <input type='hidden' name='blah' value='something' />
  
  <select multiple='multiple' name='theMulti'>
    <option value='First Choice' selected='selected'>First Choice</option>
    <option value='Second Choice'  selected='selected'>Second Choice</option>
    <option value='Third Choice' >Third Choice</option>
  </select>
</form>

Output

{blah: "something", theMulti: "First Choice"}

Expected

I would expect something like:

{blah: "something", theMulti: ["First Choice", "Second Choice"]}
@cullylarson
Copy link
Author

I came up with a solution. If you replace all of your uses of el.value with the getValue function below, multi-selects will work:

function getValue(el) {
    if(el.type !== 'select-multiple') return el.value

    if(!el.options || !el.options.length) return el.value

    const results = [...el.options].reduce(function(acc, option) {
        if(option.selected) {
            acc.push(option.value || option.text)
        }

        return acc
    }, [])

    return results.length
        ? results
        : undefined
}

@jackmoore
Copy link
Owner

My apologies for the late reply, this looks great. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants