2

I am trying to append the values from jquery to select box .

The html side is shown below

<select class="form-control prod" name="SalesPerson" id="SalesPerson"  required>
  <!-- <option value="">Select Sales Person</option> -->
</select>

Code Snippet of Ajax is shown below

success: function(data){
  console.log(data);
  $.each(data, function(key, value) {
    $('#SalesPerson').append("<option value='" + data.admin_id + "'>" + data.fname + "</option>");
  });
}
}); 

When i do console.log(data);

I get this output below

[{"admin_id":"206","fname":"FLYJAC-1BR","lname":""},{"admin_id":"252","fname":"KAMAL","lname":"G"},{"admin_id":"253","fname":"WILLIAM","lname":"S"}]

But the data is not appending to the select box . Any help appreciated.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Shreyas Achar
  • 1,407
  • 5
  • 36
  • 63

1 Answers1

2

1.dataType: 'json' need to be added to your ajax call

2.data.admin_id need to be value.admin_id and so on for other.

Working snippet:-

data = [{"admin_id":"206","fname":"FLYJAC-1BR","lname":""},{"admin_id":"252","fname":"KAMAL","lname":"G"},{"admin_id":"253","fname":"WILLIAM","lname":"S"}];
$.each(data, function(key, value) {
  $('#SalesPerson').append("<option value='" + value.admin_id + "'>" + value.fname + "</option>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control prod" name="SalesPerson" id="SalesPerson"  required>
 <!-- <option value="">Select Sales Person</option> -->

</select>

For your code need to be (As you said that you want to remove old options and then need to add new options):-

success: function(data){
    var option_html = '';
    $.each(data, function(key, value) {
        option_html += "<option value='" + value.admin_id + "'>" + value.fname + "</option>";
    });
    $('#SalesPerson').html(option_html);
}

Note:-

if you don't have dataType: 'json' in your ajax call then before $.each() code do:-

data = $.parseJSON(data);
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • This function is added for onchange of select am passing the id and retrieving the data and appending it to another select box, Now whats happening is wen i change the first select box the values are getting displayed if i change it second time the old values are not erasing/clearing. how to clear that? – Shreyas Achar Mar 29 '18 at 04:49
  • @ShreyasBandimat check my `For your code need to be (As you said that you want to remove old options and then need to add new options)`section code and try that. Thanks. – Alive to die - Anant Mar 29 '18 at 05:10