Home > database >  Add an empty option in select2 when options are created from jQuery
Add an empty option in select2 when options are created from jQuery

Time:12-14

I try to add an empty <option></option> when I set the options from jQuery but when the page is loaded the fist option is selected. I added allowClear: true, placeholder: "Select...", but it didn't worked.

I have found a walk around, to clear the option after I initialize the select2, which works but is there any better solution?

$(".select2-it").val(null).trigger('change');

var itData = [{
    id: 0,
    text: 'Apps',
    children: [{
        id: '1',
        text: 'App1'
      },
      {
        id: '2',
        text: 'App2'
      },
      {
        id: '3',
        text: 'App3'
      }
    ]
  },
  {
    id: 4,
    text: 'bug'
  },
  {
    id: 5,
    text: 'duplicate'
  }
];

$(".select2-it").select2({
  allowClear: true,
  placeholder: "Select...",
  data: itData,
  width: "100%"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />

<select id="it-target" ></select>

CodePudding user response:

You can prepend the empty option in the DOM element (using .prepend()) before calling the Select2 initializer on your input.

var itData = [{
    id: 0,
    text: 'Apps',
    children: [
        { id: '1', text: 'App1' },
        { id: '2', text: 'App2' },
        { id: '3', text: 'App3' }
    ]
}, {
    id: 4,
    text: 'bug'
}, {
    id: 5,
    text: 'duplicate'
}];

$(".select2-it").prepend('<option></option>').select2({
    allowClear: true,
    placeholder: "Select...",
    data: itData,
    width: "100%"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<select id="it-target" ></select>

  • Related