Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Html select multiple returns last value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading