skip to Main Content

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

  1. Select option from dropdown 1 postchoose
  2. Append result in dropdown 2 postdets
  3. Change option in dropdown 1 postchoose
  4. Clear options in dropdown 2 postdets
  5. Append new data to dropdown 2 postdets

one

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


  1. Chosen as BEST ANSWER

    Solved

    As I wanted it clear out second dropdown as soon as option is changed in first dropdown. Here is what I did:

    $('body').on('change', '#postchoose', function(e){
      $('select[name="postdets"]').empty().append("<option value='' selected>Processing...</option>");
      //other lines....
      $.ajax({
        url: '{{ url('rajaajax') }}/'+weight+'/'+cityID+'/'+encodeURI(courierName),
        type: "GET",
        dataType: "json",
        success:function(data) {
          $('select[name="postdets"]').empty().append("<option value='' selected>Select</option>");
          //rest of it...
        }
      });
    });
    

    Now when I change option of first dropdown it shows processing... and when data is ready it says select.

    one

    two


  2. 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.

    $.ajax({
      ...
      success: function(data) {
        $('select[name="postdets"]').empty();
        ...
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search