select2 - how to allow a null value
Asked Answered
A

3

10

In a form there are multiple select2 elements. In a particular select2 element I set some options with a not null string 'text' and null 'value'. The submit form seems to behave like this:

  • if 'value' is not null -> 'value' is the submitted item on 'submit' action
  • if 'value' is null -> 'text' is the submitted item on 'submit' action

This is not the behavior I'm looking for. How can I submit 'value' when 'value' is null? I just want to submit null! I can't find anything like that in the select2 documentation.

Annadiane answered 3/7, 2017 at 16:18 Comment(1)
Which version of Select2 are you using? That functionality may have changed with the 4.0 versions as I am seeing the same.Libyan
L
12

To specify a null value you set the Select2 value to null and the placeholder will appear.

$('select').select2({
    placeholder: 'Your NULL value caption',
    allowClear: true   // Shows an X to allow the user to clear the value.
});

There are/were ways (via a custom data adapter or previous versions) to create a null value entry that users could select. I know because that is what I previously did but that has now changed.

Select2 4.0.3: See: https://select2.org/selections

====================

IMPORTANT EDIT: As of Version 4.0.4 (yesterday) there is a fix that allows selecting options with blank or 0 option values. See: https://github.com/select2/select2/releases/tag/4.0.4

To enable this you need to add your NULL value and remove the "placeholder" and the "allowClear" options.

If you don't remove the "placeholder" option it will hide your "NULL" entry.

If you leave the "allowClear" then clicking the "X" will cause an error.

Libyan answered 25/9, 2017 at 15:48 Comment(0)
K
1

It can be done via HTML element attributes (for select2)

<select ... data-allow-clear=true >
Karolkarola answered 16/4, 2020 at 9:31 Comment(0)
N
1

I was facing same issue, i was using static files but solved this usning cdn

js cdn:

<script src%3D"https//cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.min.js"></script>

css cdn

<link href%3D"https//cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css" rel="stylesheet" />

please include these links in your css and js, and use

<script>
$(".your_class").select2({
placeholder: 'Your caption',
allowClear: true
})</script>

this will work fine

Namecalling answered 16/7, 2020 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.