1

I have data retrieved using AJAX. I need to add an empty option, '-----'. How can I do this? I tried many examples but can't find a way. So this const takes from Django filed form!It is countries, districts, settlement. I need before this data EMPTY label in field.

$('<option>').val('').text('').appendTo(#reg);
  const $dis = $('#id_dis');
  const $com = $('#id_comm');
  const $sett = $('#id_sett');

  const r_choices = choicesRegistry['id_reg'];
  const d_choices = choicesRegistry['id_dis'];
  const comm_choices = choicesRegistry['id_comm'];
  const sett_choices = choicesRegistry['id_sett'];


$reg.on('change', function() {
  // d_choices.disable();
  // c_choices.disable();
  console.log(this.value)
  if (this.value === '') {
    d_choices.disable();
  } else {
    $.ajax({
      method: 'get',
      url: '/contry',
      data: {
        level_1: this.value,
        level: 2
      },
      success: (data) => {
        // data.unshift(''),
        console.log(data)
        // d_choices.setChoiceByValue(data, 'code', true);
        d_choices.setChoices(data, 'code', 'name', true);
        d_choices.setChoiceByValue('code', 'name')
        console.log(d_choices)


        console.log(d_choices)
        d_choices.enable();
      },
    });
  }
});
Ken Ist
  • 79
  • 6
  • The question needs more context. Where are you trying to see the empty option? I assume it's something to do with the `d_choices` variable, but what does that contain? – Rory McCrossan Jul 02 '21 at 10:41
  • `setChoices` and `setChoiceByValue` are not standard JavaScript functions, this looks like a third-party widget. Can you link to the documentation? – Barmar Jul 02 '21 at 10:43
  • Why does it matter that you got the data from AJAX? Adding dynamic options to the dropdown is the same no matter where the data came from. – Barmar Jul 02 '21 at 10:44
  • https://github.com/Choices-js/Choices#setchoicebyvaluevalue This is documentation – Ken Ist Jul 02 '21 at 10:58
  • @RoryMcCrossan in d_choices countries from Django field form , I need before this countries, EMPTY field - empty option – Ken Ist Jul 02 '21 at 11:10
  • Thanks for clarifying, I added an answer for you below – Rory McCrossan Jul 02 '21 at 11:12

1 Answers1

0

The setChoices() method accepts an array of objects specifying the value and label properties of the option elements to be created. As such you can prepend a new object to this object to add the required 'empty' option:

// inside success handler:
data.unshift({ code: '', name: '-----' });
d_choices.setChoices(data, 'code', 'name', true);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339