Search code examples
javascriptjqueryajaxselectize.js

Change Selectize load url parameters


selectize({
        valueField: 'Id',
        labelField: 'Name',
        searchField: 'Name',
        load: function (query, callback) {
            $.ajax({
                url: '/some_url/params?SOME_ID=4&keyword=' + encodeURIComponent(query),
                success: function (response) {}
            });
        }
    });

in the above snippet, is it possible to change the value of SOME_ID in request params based on some event
without destroying are re initializing the whole input ?
thanks in advance

the only solution i found was to destroy and re initialize the input, but am looking for a better approach


Solution

  • Try storing the value in a suitably scoped variable.

    Since the load function is called for each search, it will be evaluated correctly.

    For example

    const selectizeQueryParams = {
      SOME_ID: 4, // initial value
    };
    
    document.addEventListener('some-event', (e) => {
      selectizeQueryParams.SOME_ID = 'newValue';
    });
    
    // ...
    
    selectize({
      valueField: 'Id',
      labelField: 'Name',
      searchField: 'Name',
      load: function (keyword, callback) {
        $.get('/some_url/params', {
          ...selectizeQueryParams,
          keyword, // 👈 jQuery automatically encodes params when passed as an object
        }).done(function (response) {});
      },
    });