Ken Ist
Ken Ist

Reputation: 79

How to add empty option in ajax

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();
      },
    });
  }
});

Upvotes: 1

Views: 223

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337704

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);

Upvotes: 0

Related Questions