Search code examples
wordpressjquery-select2toastr

WordPress with select2 and Toastr get previous selected value destroys select2 behavior


I am using WordPress and I have used Select2 and Toastr libraries successfully.

Basically I have a dropdown and if I change, Toastr will ask whether I need to update or not.

If I click on "Yes" then it will update and if I click on "No" then my dropdown should set previous value and nothing will happen.

Currently its selecting previous value but then if I open the same dropdown try to click on it to search then its saying "The results could not be loaded".

Here is my JS code what I have done so far.

var prevSubVarClientId;
jQuery('.mySubscription').select2({
    allowClear: true,
    placeholder: "",
    
    //minimumInputLength: 3,
    ajax: {
        type: "POST",
        url: '/wp-admin/admin-ajax.php',
        dataType: 'json',
        delay: 250, // delay in ms while typing when to perform a AJAX search
        data: function (params, page) {
        
        return {
            action: 'list_posts',
            q: params.term,
        };
        },
        processResults: function( data ) {
        
        var options = [];
        if ( data ) {          
            jQuery.each( data, function( index, text ) { 
            
            options.push( { id: text['id'], text: text['name']  } );
            });

        }
        return {
            results: options
        };
        },
        cache: true
    }
});

jQuery('.mySubscription').on('select2:selecting', function (evt) {
  prevSubVarClientId = jQuery('select').val();
});

jQuery('.mySubscription').change(function() {
    var $this = jQuery(this);
     jQuery(this).blur();
      alertify.confirm("Are you sure you want to transfer?",
  function(e){
        var subscriptionId = jQuery($this).data("subscription-id");
        var url = jQuery($this).data("ajax-url");        
        var userId = jQuery($this).val();        
        jQuery.ajax({
           type: "POST",
           url: url,           
            data : {
                    action : 'update_var_client_user_id',
                    userId : userId,
                    subscriptionId : subscriptionId
            },
           success: function(data)
           {  
            var data = JSON.parse(data);      
            toastr["success"]("Transferred Successfully." );          
            
           }
         });
  },
  function(){
    
    jQuery($this).val(prevSubVarClientId);    
    jQuery($this).select2().trigger('change');
    
  }).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });

    
});

As you can see I have prevSubVarClientId variable and mySubscription dropdown with this class.

jQuery('.mySubscription').change(function() { here you can see I am opening alertify confirm box and if I click on "No" then I am doing below code.

jQuery($this).val(prevSubVarClientId);    
jQuery($this).select2().trigger('change');

But then whenever I am trying to open the dropdown again, I am getting the below error.

enter image description here

Can some one guide me, what I am doing wrong here ?

Thanks


Solution

  • "The results could not be loaded". only show when return data is null or not found.

    I tested your code below snippet and working fine.

    $(".js-data-example-ajax").select2();
    
    jQuery('.js-data-example-ajax').on('select2:selecting', function (evt) {
        prevSubVarClientId = jQuery('select').val();
    });
    
    jQuery('.js-data-example-ajax').change(function() {
        var $this = jQuery(this);
        jQuery(this).blur();
        alertify.confirm("Are you sure you want to transfer?",
        function(e){
            console.log('change');
        },function(){
            console.log('no change');
            jQuery($this).val(prevSubVarClientId);    
            jQuery($this).select2().trigger('change');
        }).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
    });
    .select2-container, .select2-container--open .select2-dropdown--below {
        width: 200px !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/css/alertify.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js"></script>
    <select class="js-data-example-ajax">
      <option value="abc">ABC</option>
      <option value="bca" selected>BCA</option>
      <option value="mnp">MNP</option>
      <option value="pqr">PQR</option>
    </select>