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>