selectize.js icon indicating copy to clipboard operation
selectize.js copied to clipboard

Trigger ajax on click event every time, item is selected

Open arnisjuraga opened this issue 11 years ago • 3 comments

Hi!

I have selectize dropdown:

var $select_person = $('#select-repo').selectize({

    sortField: 'text',
    valueField: 'id',
    labelField: 'name',
    searchField: ['name', 'address'],
    options: [
    {id: "1", address: "Street1", name: "Customer1" },
    {id: "2", address: "Street2", name: "Customer2" }   
    ],  
    render: {
        option: function(item, escape) {
            var label = item.name || item.address;
            var caption = item.name ? item.address : null;

            return '<div>' +
            '<span class="label">' + escape(label) + '</span>' +
            (caption ? ' <span class="caption">' + escape(caption) + '</span>' : '') +
            '</div>';
        },

        item: function(item) {

            $.ajax({ 
                url: '/objects/objects/get_objects_json',
                dataType: 'json',
                type: 'post',
                data: { person:  item.id },
                success: function(data) {
                    /*some ajax request*/
                }
            });     

            return '<div>' +
            '<span style="color:red" class="label">'+item.name+'</span>'
            '</div>';
        },
    }

});

I want to execute ajax request everytime I click on Customer1 or Customer2, because I have dependant information on the page, which should be changed on different selected customers.

Everything works fine, untill I select any option for the second time. If I select Customer1, then Customer2 and then again - Customer1 - ajax request will not be triggered anymore.

It seems, click event is not bound to Option anymore?

See JSFiddle: https://jsfiddle.net/vtgza56m/

arnisjuraga avatar Oct 12 '15 12:10 arnisjuraga

You are triggering your Ajax calls when the selected item is rendered, but the rendered items are cached and re-used. (You can clear these by calling selectize.clearCache('item'), but see below for a better solution.)

You can instead register a callback with selectize({ onChange: function( value ) { ... } }) that will fire every time the value of the control is changed.

mcavalletto avatar Jan 22 '16 17:01 mcavalletto

Thanks, I will try!

arnisjuraga avatar Jan 22 '16 18:01 arnisjuraga

closing stale issues older than one year. If this issue was closed in error please message the maintainers. All issues must include a proper title, description, and examples.

risadams avatar Nov 12 '20 12:11 risadams