Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Selectize Add "Clear All" link at the top of options from Ajax

I am using Jquery's Selectize tagging library which works well for me so far.

Below is the code I have used.

Javascript Code:

$('#q').selectize({
    plugins: ['remove_button'],
    valueField: 'address',
    labelField: 'address',
    searchField: 'address',                 
    create: true,    
    render: {
        item: function(data, escape) {
            return '<div>' + escape(data.address) + '</div>';
        }

    },
    onChange: function(value) {
      $(".selectize-input input[placeholder]").attr("style", "width: 100%;");
    },
    load: function(query, callback) {
        if (!query.length) return callback();
        $.ajax({
            url:  base_url + '/search-property-autocomplete',
            type: 'POST',
            dataType: 'json',
            data: {
                q: query,

            },
            error: function() {
                callback();
            },
            success: function(res) {
                console.log(res.properties);
                callback(res.properties);
            }
        });
    }
});

PHP Code:

/* API for autocomplete list of properties */
Route::post('/search-property-autocomplete', function () {
    if (!empty(trim($_POST['q']))) {
        $search_term = trim($_POST['q']);


        // getting Suburb State and Postcode of the properties based on search 
        $query = Property::join('technobrave_suburbs_', function($join) {

                    $join->on('technobrave_properties_.suburb_id', '=', 'technobrave_suburbs_.id');
                });

        $query->join('technobrave_states_', function($join) {
            $join->on('technobrave_properties_.state_id', '=', 'technobrave_states_.id');
        });


        $query->select('technobrave_properties_.*', 'technobrave_suburbs_.suburb', 'technobrave_states_.state_name');

        $query->where(function($query) use ($search_term) {
            $query->where('technobrave_properties_.post_code', 'LIKE', '%' . $search_term . '%');
            $query->orwhere('technobrave_suburbs_.suburb', 'LIKE', '%' . $search_term . '%');
            $query->orwhere('technobrave_states_.state_name', 'LIKE', '%' . $search_term . '%');
        });
        $data = $query->take(8)->get(); // getting maximum 8 records only 

        if ($data) {
            foreach ($data as $current_record) {
                $result[] = array(
                    'address' => $current_record->suburb . ' ' . $current_record->state_name . ' ' . $current_record->post_code
                );
            }
        }
    } else {
        $result = [];
    }
    echo json_encode(array('properties' => $result));
});

As you can see in above code, I am using Ajax to populate data and getting records by calling my php function which is working absolutely fine.

Now, I want to append one item as a hyperlink at the top of my all the results something like Clear All which will come every time I search or type in my input-box.

And IF I click on Clear All link, the results which appended below should be cleared.

To use the clearoptions() event provided by Selectize, I have updated my create: in my JavaScript code with:

create: function(input, callback) {

    $.ajax({
        url:  base_url + '/search-property-autocomplete',
        type: 'POST',
        dataType: 'json',
        data: {
            q: query,

        },
        error: function() {
            callback();
        },
        success: function(res) {

            return callback({ address: "<a href='javascript:void(0)'>Clear All</a>" });

        }
    });


},

But it seems to be not working as I am unable to see my added option there. I am unable to see my Hyperlink after my results populate.

I already know using somethink like below code will remove my populated records after I search.

$('.my-hyperlink-custom-class').on('click', function() {
    control.clearOptions();
});

But I am stuck appending or pushing this new item to my code with the results I populate using Ajax.

Can someone guide me how can I achieve this.

like image 778
Mittul At TechnoBrave Avatar asked Sep 13 '17 12:09

Mittul At TechnoBrave


1 Answers

Thank you so much to all for help and support. And special thanks to @afeique's hint to implement this feature.

Here is the solution I eventually came up with.

$('#q').selectize({
    plugins: ['remove_button'],
    valueField: 'address',
    labelField: 'address',
    searchField: 'address',                 
    create: true,    
    render: {
        item: function(data, escape) {
            return '<div>' + escape(data.address) + '</div>';
        }

    },
    onChange: function(value) {
      $(".selectize-input input[placeholder]").attr("style", "width: 100%;");
    },
    load: function(query, callback) {
        if (!query.length) return callback();

        // Appending only if not exists 
        if($('.clearAllSuggestions').length == 0) {
            $(".selectize-dropdown").append('<a href="#" class="clearAllSuggestions">Clear All</a>');
        }
        $.ajax({
            url:  base_url + '/search-property-autocomplete',
            type: 'POST',
            dataType: 'json',
            data: {
                q: query,

            },
            error: function() {
                callback();
            },
            success: function(res) {
                console.log(res.properties);
                callback(res.properties);
            }
        });
    }
});


$('body').on('click', '.clearAllSuggestions', function() {

    var $select = $('#q').selectize({});
    var control = $select[0].selectize;
    control.clearCache('option');
    control.clearOptions();
    control.refreshOptions(true);
});

I modified my code a bit and put below code in my load event to append "Clear All" anchor tag in my suggestion tag options.

// Appending only if not exists 
        if($('.clearAllSuggestions').length == 0) {
            $(".selectize-dropdown").append('<a href="#" class="clearAllSuggestions">Clear All</a>');
        }

Then, I simply wanted to clear cache and options hence I put below code.

$('body').on('click', '.clearAllSuggestions', function() {

    var $select = $('#q').selectize({});
    var control = $select[0].selectize;
    control.clearCache('option');
    control.clearOptions();
    control.refreshOptions(true);
});

Hope this helps.

like image 158
Mittul At TechnoBrave Avatar answered Oct 21 '22 11:10

Mittul At TechnoBrave