Home > database >  Html select multiple returns last value
Html select multiple returns last value

Time:01-26

I have gone through this and several other examples the code simply doesn't work when I pprint on the backend of django.

<select name="multiple-select[]" id="multiple-select" multiple>
    <option value="1">Books</option>
    <option value="2">Movies, Music & Games</option>
    <option value="3">Electronics & Computers</option>
    <option value="4">Home, Garden & Tools</option>
    <option value="5">Health & Beauty</option>
    <option value="6">Toys, Kids & Baby</option>
    <option value="7">Clothing & Jewelry</option>
    <option value="8">Sports & Outdoors</option>
</select>

When I select multiple items, the last item is what will be printed out not an array of items as expected.

CodePudding user response:

In Django, when you submit a form with a multiple select element, the selected values will be sent as a string in a comma-separated format. To access the selected values as a list, you can use the request.POST.getlist() method.

For example:

selected_values = request.POST.getlist('multiple-select')

This will return the selected items as a list of strings.

You can also use the request.POST.get() method, which will return a string with comma separated values

selected_values = request.POST.get('multiple-select')
selected_values = selected_values.split(',')

You can then use this list to filter or perform any other operations you need on the selected values.

Please note that, in your HTML snippet, you have a select element with the name multiple-select[], you can use that instead of the multiple-select in the above code snippet.

  • Related