0

I perform a AJAX call to retrieve some data to populate a drop-down menu based on a user selection. I get the data fine, but am not able to select the new added/appended options, even though they appear in the console. I am doing this inside the AJAX success parameter -

<div class="row">
<div class="select-field col s12 required">
  <label>Manufacturer</label>
  <select id="Manufacturer_options" name="Manufacturer_options">
           <option value = "" disabled selected> Select Manufacturer</option>


  </select>
</div>
</div>




$.ajax({
url: .....
data: ......
dataType: 'json',

success: function(data) {    

  select = document.getElementById('Manufacturer_options')
  var opt = document.createElement('option');
      opt.innerHTML = 'test'
      select.appendChild(opt)

.
.
.});

Instead of "appendChild", I have also tried "add", "append", as well as building a string and appending that. The option is there when I open the Chrome debugger and inspect the element:

enter image description here

But I cannot open my dropdown, as there are no options outside the hardcoded value disabled option:

enter image description here

mk8efz
  • 1,374
  • 4
  • 20
  • 36
  • change `select.appendChild(opt)` to `$(select).append(opt)` – Joe Lissner May 12 '17 at 16:53
  • @JoeLissner select.appendChild(opt) is fine. – James May 12 '17 at 16:55
  • @James you are correct, my bad. – Joe Lissner May 12 '17 at 16:56
  • 1
    @JoeLissner, it appears as though you are using a library of some kind to give the material design look and feel to your select. You likely need to refresh the design element so that it understands that you have added an option. – Shaun Frisbee May 12 '17 at 17:05
  • Good eye, this post answered my question (it was due to the materialize css framework): http://stackoverflow.com/questions/29132125/how-to-dynamically-modify-select-in-materialize-css-framework?rq=1 – mk8efz May 12 '17 at 20:53

2 Answers2

0

Your code works, assuming the ajax part is ok and you mentioned that in devtools you see the element. I've taken out the ajax part here. Perhaps something else on your page is causing the problem.

  select = document.getElementById('Manufacturer_options');
  var opt = document.createElement('option');
  opt.innerHTML = 'test';
  select.appendChild(opt);
<div class="row">
<div class="select-field col s12 required">
  <label>Manufacturer</label>
  <select id="Manufacturer_options" name="Manufacturer_options">
           <option value = "" disabled selected> Select Manufacturer</option>
  </select>
</div>
</div>
James
  • 20,957
  • 5
  • 26
  • 41
0

As another commenter mentioned, the issue was with the materialize css library. I just needed add this to the bottom of the AJAX code:

$('#Manufacturer_options').material_select();

For more information, see this question:

How to dynamically modify <select> in materialize css framework

Community
  • 1
  • 1
mk8efz
  • 1,374
  • 4
  • 20
  • 36