Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 - how to allow a null value

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.

like image 649
user1403546 Avatar asked Jul 03 '17 16:07

user1403546


2 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.

like image 73
AnthonyVO Avatar answered Oct 01 '22 08:10

AnthonyVO


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

<select ... data-allow-clear=true >
like image 33
Yevgeniy Afanasyev Avatar answered Oct 01 '22 09:10

Yevgeniy Afanasyev