select2 - how to allow a null value

Viewed 13952

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.

3 Answers

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.

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

<select ... data-allow-clear=true >

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

Related