I have ajax code that return data from API based on selected option in dropdown, the problem is when I change dropdown option it will not clear old data and just add new data to previous ones in my append.
Logic
- Select option from dropdown 1
postchoose
- Append result in dropdown 2
postdets
- Change option in dropdown 1
postchoose
- Clear options in dropdown 2
postdets
- Append new data to dropdown 2
postdets
Code
$('body').on('change', '#postchoose', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $("#city option:selected").val();
var weight = ["{{$totalWeight}}"];
var courierName = $(this).val();
if(courierName) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+cityID+'/'+encodeURI(courierName),
type: "GET",
dataType: "json",
success:function(data) {
// append data
$('select[name="postdets"]').append('<option>test</option');
}
});
} else {
$('select[name="postdets"]').empty().append("<option value='' selected>Pilih</option>");
}
});
Question
How to clear my append part success:function(data) {
when courierName
is changed before new data appends?
2
Answers
Solved
As I wanted it clear out second dropdown as soon as option is changed in first dropdown. Here is what I did:
Now when I change option of first dropdown it shows
processing...
and when data is ready it saysselect
.It seems that you did not clear
$('select[name="postdets"]')
before appending a new option. You can try add$('select[name="postdets"]').empty()
immediately after success function.