2

I need to append a HTML select option using jQuery. I have a piece of code that when a drop down is clicked, it fetches sub functions via AJAX. Once this is done, I also need to to add another option tag with a value of 99 and text of Other sub function. My code:

$.ajax({
    type: "POST",
    data: {function_id: function_id},
    url: '<?php echo WEB_URL; ?>includes/ajax/target_audience_sub_functions.php',
    dataType: 'json',
    success: function(json) {
        var $el = $("#target_audience_sub_function");
        $el.empty(); // remove old options
        $el.append($("<option></option>").attr("value", '').text('Please Select'));
        $.each(json, function(value, key) {
            $el.append($("<option></option>").attr("value", value).text(key));
        });
        $el.append($("<option></option>").attr("value", '99').text('Other sub function'));
    }
});

The $el.append is the code I am trying to use to add the other option tag, but it doesn't work. I only get the ones from the AJAX. incidentally, the first append doesn't work either.

HTML

<div class="form-group">
    <label for="target_audience_sub_function">Sub-Function</label>
                  <select data-selectedSubFunction="<?php echo (isset($audience)) ? $audience['target_audience_sub_function'] : ''; ?>" class="form-control light_grey_bg ta_sub_function" id="target_audience_sub_function" name="target_audience_sub_function[]">
                      <option value="">-- Choose sub function --</option>
                      <?php $get_functions = $db->get_all('sub_functions');
                        foreach ($get_functions as $function) { ?>
                            <option value="<?php echo $function['sub_function_id']; ?>" <?php echo isset($audience) ? $audience['target_audience_sub_function'] == $function['sub_function_id'] ? "selected='selected'" : "" : ''; ?> ><?php echo $function['sub_function_name']; ?></option>
                       <?php } ?>
                  </select>
              </div>
Pete Naylor
  • 776
  • 2
  • 14
  • 33

1 Answers1

2

Your code should work, I just tried it and the select got populated as you want it.

var json = {
  0: 'Hello',
  1: 'Bobby'
};
$(function() {
  var $el = $("#target_audience_sub_function");
  $el.click(function() {
    $el.empty(); // remove old options
    $el.append($("<option></option>").attr("value", '').text('Please Select'));
    $.each(json, function(value, key) {
      $el.append($("<option></option>").attr("value", value).text(key));
    });
    $el.append($("<option></option>").attr("value", '99').text('Other sub function'));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="target_audience_sub_function"></select>

Maybe the success callback is never executed and the options you see are the one printed by PHP ?

DaniP
  • 37,813
  • 8
  • 65
  • 74
Dondosh
  • 46
  • 4