Home > OS >  HTML Multiple select not returning array
HTML Multiple select not returning array

Time:01-21

I'm trying to make a web application using express and I'm trying to make a form to create a new product. In there I have multiple select to select the categories for the product. Here is my code for the multi-select:

<div >
        <label for="categories" >Categories:</label>
        <div >
            <select multiple name="product[categories[]]" id="categories" >
                <% for (let category of categories) { %>
                <option value="<%= category.id %>">
                    <%= category.name %>
                </option>
                <% } %>
            </select>
        </div>
    </div>

The target is for it to fill in the products.categories field with an array of categories. But this is what I receive on the server:

{
  product: {
    name: 'Nvidia GeForce RTX 4090',
    price: '1499.99',
    description: 'State-of-the-art GPU. Recently released with unrivalled performance. Take your gaming to the next level!',
    discountedPrice: '',
    stock: '5'
  },
  'product[categories': [ '63a18514fade00e8bc7f4d1c' ]
}

It doesn't seem to want to format the array properly and I'm unsure as to why this is. I've already tried removing the second brackets in the name field to get

product[categories]

But then it doesn't return an array when just a single item is selected.

Is there an alternative way of me doing this or should I just use the above and convert it to an array on the server?

CodePudding user response:

It looks like the issue is with the name attribute of the select element. The brackets in the name attribute are causing the server to interpret the categories as an object rather than an array.

One way to fix this would be to remove the brackets from the name attribute and then on the server side, use the req.body.product.categories to convert it into an array. You can use the Array.isArray() method to check if the categories is already an array, if not use the Array.of() method to convert it into an array.

Another way to fix this would be to change the name attribute to product.categories[]. This way, when the form is submitted, the categories will be sent as an array in the request body.

If you're using express-validator for validating the form, you can also use the array method to validate the categories field as an array.

So you can use either of these methods, but it's best to convert it to an array on the server-side to make sure the data is properly formatted before storing it in the database.

CodePudding user response:

It works without extra server-side code if you change the name to

<select multiple name="product[categories]">

(without the nested brackets). Then a query like

?product[categories]=a&product[categories]=b

will be parsed into

req.query = {"product":{"categories":["a","b"]}}
  • Related