Code Monkey home page Code Monkey logo

ajax-bootstrap-select's Introduction

Ajax Bootstrap Select GitHub version Build Status CDNJS Gitter FOSSA Status

Getting Started

Extends existing Bootstrap Select implementations by adding the ability to search via AJAX requests as you type. Originally for CROSCON.

Requirements

Minimum requirements:

Bootstrap Select must either be be initialized with liveSearch enabled in the passed options or the select element must have the data-live-search="true" attribute.

This plugin must be initialized after Bootstrap Select has been initialized. For a more detailed explanation on implementation, see usage example.

Suggested requirements:

Options

Options can be passed via data attributes or through the JavaScript options object. For data attributes, append the option name to the data-abs- prefix. Options names (and any nested options) are always lower case and separated by -, such as in data-abs-ajax-url="..." or data-abs-locale-search-placeholder="...".

options.ajaxResultsPreHook

Deprecated: Since version 1.2.0, see: options.preprocessData.

Type: Function


options.ajax

Required

Type: Object

Data Attribute: data-abs-ajax[-*]="..."

The options to pass to the jQuery AJAX request.

{
    url: null, // Required.
    type: 'POST',
    dataType: 'json',
    data: {
        q: '{{{q}}}'
    }
}

options.minLength

Type: Number

Default: 0

Data Attribute: data-abs-min-length="..."

Invoke a request for empty search values.


options.ajaxSearchUrl

Deprecated: Since version 1.2.0, see: options.ajax.

Type: String


options.bindEvent

Type: String

Default: "keyup"

Data Attribute: data-abs-bind-event="..."

The event to bind on the search input element to fire a request.


options.cache

Type: Boolean

Default: true

Data Attribute: data-abs-cache="..."

Cache previous requests. If enabled, the "enter" key (13) is enabled to allow users to force a refresh of the request.


options.clearOnEmpty

Type: Boolean

Default: true

Data Attribute: data-abs-clear-on-empty="..."

Clears the previous results when the search input has no value.


options.clearOnError

Type: Boolean

Default: true

Data Attribute: data-abs-clear-on-error="..."

Clears the select list when the request returned with an error.


options.debug

Deprecated: Since version 1.2.0, see: options.log.

Type: Boolean


options.emptyRequest

Type: Boolean

Default: false

Data Attribute: data-abs-empty-request="..."

Invoke a request for empty search values.


options.ignoredKeys

Type: Object

Data Attribute: data-abs-ignored-keys[-*]="..."

Key codes to ignore so a request is not invoked with bindEvent. The "enter" key (13) will always be dynamically added to any list provided unless the "cache" option above is set to "true".

{
    9: "tab",
    16: "shift",
    17: "ctrl",
    18: "alt",
    27: "esc",
    37: "left",
    39: "right",
    38: "up",
    40: "down",
    91: "meta"
}

options.langCode

Type: String

Default: null

Data Attribute: data-abs-lang-code="..."

The language code to use for string translation. By default this value is determined by the browser, however it is not entirely reliable. If you encounter inconsistencies, you may need to manually set this option.


options.locale

Type: Object

Default: null

Data Attribute: data-abs-locale[-*]="..."

Provide specific overrides for locale string translations. Values set here will cause the plugin to completely ignore defined locale string translations provided by the set language code. This is useful when needing to change a single value or when being used in a system that provides its own translations, like a CMS.

locale: {
    searchPlaceholder: Drupal.t('Find...')
}

options.log

Type: String|Number|Number

Default: 'error'

Data Attribute: data-abs-log="..."

Determines the amount of logging that is displayed:

  • 0, false: Display no information from the plugin.
  • 1, 'error': Fatal errors that prevent the plugin from working.
  • 2, 'warn': Warnings that may impact the display of request data, but does not prevent the plugin from functioning.
  • 3, 'info': Provides additional information, generally regarding the from request data and callbacks.
  • 4, true, 'debug': Display all possible information. This will likely be highly verbose and is only recommended for development purposes or tracing an error with a request.

options.mixWithCurrents

Deprecated: Since version 1.2.0, see: options.preserveSelected.

Type: Boolean


options.placeHolderOption

Deprecated: Since version 1.2.0, see: locale.emptyTitle.


options.preprocessData

Type: Function|null

Default: function(){}

Process the raw data returned from a request. The following arguments are passed to this callback:

  • data - Array The raw data returned from the request, passed by reference. This callback must return one of the following:
  • Array - A new array of items. This will replace the passed data.
  • undefined|null|false - Stops the callback and will use whatever modifications have been made to data.
function (data) {
    var new = [], old = [], other = [];
    for (var i = 0; i < data.length; i++) {
        // Add items flagged as "new" to the correct array.
        if (data[i].new) {
            new.push(data[i]);
        }
        // Add items flagged as "old" to the correct array.
        else if (data[i].old) {
            old.push(data[i]);
        }
        // Something out of the ordinary happened, put these last.
        else {
            other.push(data[i]);
        }
    }
    // Sort the data according to the order of these arrays.
    return [].concat(new, old, other).
}

options.preserveSelected

Type: Boolean

Default: true

Data Attribute: data-abs-preserve-selected="..."

Preserve selected items(s) between requests. When enabled, they will be placed in an <optgroup> with the label Currently Selected. Disable this option if you send your currently selected items along with your request and let the server handle this responsibility.


options.preserveSelectedPosition

Type: String

Default: 'after'

Data Attribute: data-abs-preserve-selected-position="..."

Place the currently selected options 'before' or 'after' the options returned from the request.


options.processData

Type: Function|null

Default: function(){}

Process the data returned after this plugin, but before the list is built.


options.requestDelay

Type: Number

Default: 300

Data Attribute: data-abs-request-delay="..."

The amount of time, in milliseconds, that must pass before a request is initiated. Each time the options.bindEvent is fired, it will cancel the current delayed request and start a new one.


options.restoreOnError

Type: Boolean

Default: false

Data Attribute: data-abs-restore-on-error="..."

Restores the select list with the previous results when the request returns with an error.


options.templates

Type: Object

Data Attribute: data-abs-templates[-*]="..."

The DOM templates used in this plugin.

templates: {
    // The placeholder for status updates pertaining to the list and request.
    status: '<div class="status"></div>',
}

Locale Strings

See: options.locale

locale.currentlySelected

Type: String

Default: 'Currently Selected'

The text to use for the label of the option group when currently selected options are preserved.


locale.emptyTitle

Type: String

Default: 'Select and begin typing'

The text to use as the title for the select element when there are no items to display.


locale.errorText

Type: String

Default: ''Unable to retrieve results'

The text to use in the status container when a request returns with an error.


locale.searchPlaceholder

Type: String

Default: 'Search...'

The text to use for the search input placeholder attribute.


locale.statusInitialized

Type: String

Default: 'Start typing a search query'

The text used in the status container when it is initialized.


locale.statusNoResults

Type: String

Default: 'No Results'

The text used in the status container when the request returns no results.


locale.statusSearching

Type: String

Default: 'Searching...'

The text to use in the status container when a request is being initiated.


locale.statusTooShort

Type: String

Default: 'Please enter more characters'

The text used in the status container when the request returns no results.


JSON Results

The plugin expects a certain result structure, an array of objects with the objects following a certain structure, below is an example with every option set:

[
    {
        value: 'string',    // Required.
        text: 'string',     // If not set, it will use the value as the text.
        class: 'string',    // The CSS class(es) to apply to the option element.
        disabled: false,     // {Boolean} true|false

        // NOTE: If "divider" is present as a property, the entire item is
        // considered a divider and the rest of the item value/data is
        // ignored. Alternatively, this can be set in the data property as well.
        divider: true,

        // Data attributes that you would set on the option tag, these will be
        // set on the newly created options tags and the selectpicker plugin
        // will process them accordingly.
        data: {
            divider: true,
            subtext: 'string',
            icon: 'class-name', // Icon class name ex: icon-glass
            content: '<div class="custom-class">my value label</div>',
        }
    }
    ....
]

Usage Example

$('.select-picker')
    .selectpicker({
        liveSearch: true
    })
    .ajaxSelectPicker({
        ajax: {
            url: '/server/path/to/ajax/results',
            data: function () {
                var params = {
                    q: '{{{q}}}'
                };
                if(gModel.selectedGroup().hasOwnProperty('ContactGroupID')){
                    params.GroupID = gModel.selectedGroup().ContactGroupID;
                }
                return params;
            }
        },
        locale: {
            emptyTitle: 'Search for contact...'
        },
        preprocessData: function(data){
            var contacts = [];
            if(data.hasOwnProperty('Contacts')){
                var len = data.Contacts.length;
                for(var i = 0; i < len; i++){
                    var curr = data.Contacts[i];
                    contacts.push(
                        {
                            'value': curr.ContactID,
                            'text': curr.FirstName + ' ' + curr.LastName,
                            'data': {
                                'icon': 'icon-person',
                                'subtext': 'Internal'
                            },
                            'disabled': false
                        }
                    );
                }
            }
            return contacts;
        },
        preserveSelected: false
    });

License

Copyright (c) 2019 Adam Heim, contributors.
Released under the MIT license

FOSSA Status

ajax-bootstrap-select's People

Contributors

angelxmoreno avatar bercut497 avatar burakcakirel avatar danielmariz avatar debueb avatar gpedro avatar haginaga avatar kennynaoh avatar lfolk avatar liiva avatar lisurc avatar luanfonceca avatar markhalliwell avatar martenb avatar masterix21 avatar maxvyaznikov avatar miki995 avatar mitchellklijs avatar renhammington avatar rjaros avatar robotomarvin avatar tommyschmiedel avatar truckingsim avatar tweichart avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ajax-bootstrap-select's Issues

Allow replaceValue method to work with with strings

Hi again,

I am using your plugin with a .NET Script Service. These expect their parameters as a stringified JSON object, like this:

data: JSON.stringify({ 'pattern': '{{{q}}}' })

While the request itself works fine that way, the plugin fails to replace {{{q}}} in there. I worked around that like this:

if (typeof (this.options.data) == 'string')
    this.options.data = this.options.data.replace('{{{q}}}', this.plugin.query);
else
    this.plugin.replaceValue(this.options.data, '{{{q}}}', this.plugin.query);

I would be very thankful if you would integrate this possibility into your replaceValue() function.

Thank you,

Christophe

How do I put default values in multiselect

I need to include selected values by default. What I mean is to put pre selected values when I initialize the ajax bootstrap select. I tried using .selectpicker('val',[]) and it puts the values selected but not with the ajax bootstrap select styles, and when I want to add a new value typing on the search input the preselected values are deleted.

Look into adding infinite scroll

This will more than likely have to go into another file that would be included on the page rather than in the core (or we release a version with infinite scroll and version without), but don't want to bloat the core bigger than it needs to be.

TYPO mistake

Rename 'disable' to 'disabled' attribute in the readme in #json-results and #usage-example paragraphs.

{
    ....
    disable: false,     // {Boolean} true|false
    ....
}

locale.emptyTitle prevents selection value from displaying

Hello. Here is new issue:

I click on select-picker to open it, then I type text and wait for results, then I click on one of result items and it is not selects it but just close dropdown!

Here is my configuration:

var mp = $('.model-picker');
mp.selectpicker({
    width: '100%',
    noneSelectedText: mp.data('none-selected-text'),
    noneResultsText: mp.data('none-results-text')
}).ajaxSelectPicker({
    ajaxOptions: {
        url: null,
        data: {pattern: '{{{q}}}'},
        dataType: 'json',
        type: 'GET'
    },
    preserveSelected: false,
    emptyRequest: true,
    requestDelay: 600,
    locale: {
        emptyTitle: mp.data('none-selected-text'),
        searchPlaceholder: mp.data('search-placeholder'),
        statusInitialized: mp.data('search-placeholder'),
        statusNoResults: mp.data('status-no-results'),
        statusSearching: mp.data('status-searching')
    }
});

This bug apears in 1.2.0

Dynamic Refreshing

Hi,

I'm building a football fixture page that I can use to create the matches, so in other words:

Home Team (Select 1) | Away Team (Select 2)

This works fine, and pulls the data from SQL as expected. However, I also want to be able to create more than one row, in my case, more than one match per day, so it would look like this:

Home Team (Select 1) | Away Team (Select 2)
Home Team (Select 3) | Away Team (Select 4)
Home Team (Select 5) | Away Team (Select 6)

So again I have this working, except for the select boxes are simply loading just the search box, and seemingly have no functionality. This is the code I've got for my 'add' button (I've taken some unnecessary stuff out, so I may have missed a </div> - ignore if that's the case)

jQuery(document).ready(function($){
    $('.add').click(function(){
        var n = $('.alert').length + 1;
        var box_html = $('<div class="alert alert-warning alert-dismissible" role="alert"><div class="form-group"><label for="home_team">Home Team</label><div class="input-group"><select class="select-picker with-ajax" data-width="100%" data-live-search="true" name="home_team[]" id="home_team' + n + '"></select></div></div></div><div class="col-sm-6"><div class="form-group"><label for="away_team">Away Team</label><div class="input-group"><select class="select-picker with-ajax" data-width="100%" data-live-search="true" name="away_team[]" id="away_team' + n + '"></select></div></div></div>');
        box_html.hide();
        $('.my-form div.alert:last').after(box_html);
        box_html.fadeIn('slow');
        $('.select-picker').selectpicker('refresh');
        return false;
    });
});

I'm not too clued up on jQuery or Javascript, but I get the below:
Second Row not working

I've tried using $('.select-picker').selectpicker('refresh'); in the vain hope this would work, but I think I may be misguided, or just uneducated ๐Ÿ˜„ Is there something I'm doing wrong?

For info, here is my javascript code for the select boxes:

    var options = {
        ajax: {
            url: 'ajax.php',
            type: 'POST',
            dataType: 'json',
            data: {
                q: '{{{q}}}'
            }
        },
        locale: {
            emptyTitle: 'Select and Begin Typing'
        },
        langCode: 'en',
        log: 1,
        preprocessData: function (data) {
            var i, l = data.length, array = [];
            if (l) {
                for(i = 0; i < l; i++){
                    array.push($.extend(true, data[i], {
                        text: data[i].Name,
                        value: data[i].ID,
                    }));
                }
            }
            return array;
        }
    };
  $('.select-picker').selectpicker().filter('.with-ajax').ajaxSelectPicker(options);

Get values from another input or select when it change

Hi.. first of all, thanks for this plugin because it is great and it helps me with something I am creating...

I have the following problem:

  1. Lets say that this is the ajax part of the picker options for a SELECT_2:

    ajax: {
    url: app_url + '/load_values',
    type: 'POST',
    dataType: 'json',
    // Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
    // automatically replace it with the value of the search query.
    data: {
    q: '{{{q}}}'
    ,'_token': $('input[name="_token"]').val()
    ,'id': $('input[name="form_id"]').val()
    ,'version': $('input[name="version"]').val()
    ,'main_id': $('input[name="main_id"]').val()
    ,'parent': $('select#SELECT_1').val()
    ,'field': ''
    }
    }

  2. I call the plugin and it works as it is suppose to work: $(this).selectpicker({liveSearch: true}).ajaxSelectPicker(picker_options);

  3. The problem I'm having is that the plugin is getting the first value of $('select#SELECT_1').val() when it is called. I want the plugin to get the current value when it is called. Problem is that value is static and I need to get dynamically the values of $('select#SELECT_1').val().. how can I do that? is it possible?

Replace initialization "hack' with a proper event listener

https://github.com/truckingsim/Ajax-Bootstrap-Select/blob/master/src/js/classes/AjaxBootstrapSelect.js#L246-L251

This code uses a setTimeout in a very hack-ish way (basically, hope that bootstrap-select has been initialized first within 500ms). This is really unreliable and should be listening for an event instead.

We're actually waiting for the bootstrap-select project to create an initialized event that they themselves will trigger after their plugin has been created (see snapappointments/bootstrap-select#1026).

This will allow us to ensure that bootstrap-select has indeed initialized before attempting to initialize our plugin.

When options are rebuilt from cache, the change event isn't triggered

Scenario to reproduce:

  • search initial query (no cache)
  • list is populated, change is fired
  • select item, change is fired (here you can actually link to other logic to check for the selected value)
  • search for second query (no cache) - same behavior
  • search a third time - options are destroyed, selected item is None - change event not fired
  • use first query (from cache)
  • list is populated, change is not fired
  • don't select anything.

At this stage, the state of the system is:

  • option list is based on first query, built from cache
  • no item is selected
  • the last selected value you can get is from a previous step, making it impossible to have consistent logic in binding behaviors to other DOM elements.

In practice, you might want to have dependable selects and this prevents achieving that. Typically, it should work in such manner that whenever the first select changes value, the second select is enabled and it's query is enhanced so you can filter on related options.

On change problem

I'm with a problem in the onchange trigger of select.
While I'm doing research via ajax the on change trigger of the select is called multiple times.
The "on change" should be done differently?
I'm placing down the script I made for my test environment to simulate the error:

<select name="country" class="form-control" required="required" data-live-search="true"></select>

<script>

    $(document).ready(function() {

        $('select[name=country]').selectpicker().ajaxSelectPicker({
            cache: false,
            preserveSelected: false,
            ajaxOptions: {
                url: 'http://beta.json-generator.com/api/json/get/HPmtU2d',
                type: 'POST',
                dataType: 'json',
                data: function () {

                    var params = {
                        q: '{{{q}}}'
                    };

                    return params;
                }
            }
        }).on('change', function() {
            console.log('Changed!');
        });
    });

</script>

Set default data programatically

I cannot use selectpicker('val', 'data') or anything like that to set the default selected item. Lets say that for example I am editing a record, how do I set the data that the record previously had? I am talking about single select.

I have tried using the selectpicker.val('data') or selectpicker('val', 'data') and also called 'render' or 'refresh' after and nothing works.

I also tried to programatically trigger the search to search for the previously selected item but programatically I don't know how to.. I tried forcing a value into the search input in .bs-searchbox but this didn't work either.. kind of need this asap! thanks in advance.

Set first value (Previously selected value)

Excuse me, but how I can set first selected value to selectpicker when page loading first.
If I create simple html <options 'selected'> ...
Selected value applyed, but when I start search - selected value cleared , and when I select from search result new selected value not dIsplayed.( IE 11 , chrome)

Keyboards action not working

Hello,
Thanks for writing this plugin.
I'm having some issues with the keyboard behaviors. For example :

The arrows up and down keys do not scan through the content, hence blocking keyboard only navigation

The enter button does not select a value.

Thoses are currently standaard behaviors in the bootstrap select plugin. Is there a way to restore this functions ?

thanks in advance.

Using ajax with preselected option

Hi,

I'm trying to use the ajax select with an update form, like the example in this fiddle: http://jsfiddle.net/okbnumdc/10/. Basically, before the first ajax is sent, I already want to have one option selected.

What I did is I took a working example (http://jsfiddle.net/okbnumdc/9/) and just added an existing option to the select list with an attribute "selected". It is shown as selected at first, but when I try to choose a different option, the select message turns to "Select and Begin Typing". Is there a bug with preselecting an option?

Best regards,
Gregor

Options via data attributes

I want to pass options via data attributes

<select name="GLOBALSUBJID" class="form-control select-picker" 
                        data-abs-locale-empty-title="ะŸั€ะตะดะผะตั‚ ะฝะต ะฒั‹ะฑั€ะฐะฝ"
                        data-abs-locale-status-searching="ะŸะพะธัะบ...">
                    </select>

but strings don't change, if through the Javascript options object then all is well.

This problem with locale only

min query length

Is there a way to configure the min query length before trigger the search?

Load options via ajax

I need to load the options from ajax in to a selectpicker AFTER select one option in another selectpicker, who i can do that?

Locale string do not allow HTML

The locale strings are inserted with $.text() instead of $.html(). This prevents any overrides from injecting additional markup that may be needed.

Bug with selection on ie10

Hello,
I found a bug with your plugin and ie10. Yon can just try it with the exemple in the plugin directory (/example/php/).
With the multiple selectpicker, try to write anything, then select all, and try to deselect all.
We can't deselect options and they are all selected or not every other time.

Do you have any idea to fix it ?

thanks

Trigger search after pasting

With Bootstrap Select it's possible to paste text to trigger the livesearch. This functionality is broken with this plugin. After pasting text you'd have to add an extra character and remove it to trigger the livesearch.

Issue while re-rendering drop down

Hi, i am using this with bootstrap admin template,i have 5 dropdowns in a form,i will go step wise1 for implementation.
Step1 :
Dropdown1 = dd1 is initialized and after making ajax call for dd1 i also get some data for other dropdowns like dd2,dd3,dd4.

$("#dd1").selectpicker({
        liveSearch: true
    })
    .ajaxSelectPicker({
        ajax: {
            url: 'index.php?/fetch_data/get_organization_name',
            dataType : 'json',
            data: function () {
                var params = {
                    search_text: '{{{q}}}'
                };
                return params;
            }
        },
        locale: {
            emptyTitle: 'Search for your organization...'
        },
        preprocessData: function(data){
            var mydata = [];
            if(data.hasOwnProperty('organizationData')){
              var len = data.organizationData.length;
               for(var i = 0; i < len; i++){

                    var curr = data.organizationData[i];
                    mydata.push({

                      'value': curr.myvalue,
                      'text': curr.mytext ,
                      'disabled': false,

                    })

                }    
                return mydata;
            }else{
                mydata.push({

                      'value': "new",
                      'text': "Add New Organization",
                      'disabled': false

                    })
                return mydata;
             }

        },
        preserveSelected : false    
    }).change(function(){
              var myselect = $('#organization').val();
             if(myselect && myselect != "new"){
                get_all_organizatin_data(myselect);
             }else if(myselect == "new"){
               add_new_organization();
             }
      });

and pass data to them as follows.
Inside get_all_organizatin_data(myselect);

if(response_data.hasOwnProperty('city_id')){
              get_dd2_search(response_data.city_name,response_data.city_id);
            }

Code for get_dd2_search() function, this can also optionally get called when i click on dd2 from html form
Step2 :

function get_dd2_search(mytitle,myvalue){
        var option_title = ''; option_title = mytitle;
        var option_value = ''; option_value = myvalue;
        $("#dd2").html("<option value='"+option_value+"' selected='selected'>"+option_title+"</option>");  
        $("#city").selectpicker({
        liveSearch: true
    })
    .ajaxSelectPicker({
        ajax: {
            url: 'index.php?/fetch_data/get_city_data',
            dataType : 'json',
            data: function () {
                var params = {
                    city: '{{{q}}}'
                };
            }
        },
        locale: {
            emptyTitle: option_value
        },
        preprocessData: function(data){
            var mydata = [];
            if(data.hasOwnProperty('cityData')){
              var len = data.cityData.length;
               for(var i = 0; i < len; i++){

                    var curr = data.cityData[i];
                    mydata.push({

                      'value': curr.myvalue,
                      'text': curr.mytext ,
                      'disabled': false,

                    })

                }    
                return mydata;
            }else{
                mydata.push({
                      'value': "new",
                     'text': "Add New City",
                      'disabled': false
                    })
                return mydata;
             }

        preserveSelected: false
        }
      });
    }

As you can see when i call this function from dd1,data passed from dd1 is accepted and show in dd2 for emptytitle,But now when i click on dd2 & when search is fired and json data is accepted, but it is not show on dd2 emptytitletitle. emptytitle does not get refreshed with new data of dd2.
This was ISSUE NO 1
Similarly
STEP3
If i initial click on dd2 ,search is fired and json is accepted and value is show for emptytitle, BUT
STEP4
Now when i click on dd1,serach is fired ,data is accepted and now when passed to dd2 it get injected in select box but emptytitle does not get refreshed.
This was ISSUE NO 2
Kindly help me solve this.

2.0.0 roadmap

I think we work on ripping out the hackiness that we have because we didn't have events.
I think we have also deprecated the old features long enough.

  • So bump up the min version of bootstrap-select to the version that added events
  • Rip out hacky code for starting up bootstrap-select
  • Rip out code that deals with deprecation

[Proposal] Use dataSource to store object items and events

Hi, this plugin is awesome, but i think would be better if offers the possibility to have a dataSource or something like that, why?, keep reading :D...

I'm working on a project using this plugin, but in some cases, i need execute some function on select event, the problem is when that function needs a field of the object represented in the options list, for example, in my project, the ajax request return a client list, where the client's id is the 'value' and the client's name is the 'text' shown on the options list of the plugin, i need execute a function for validate or show something using/depending of another field of the client, like status or email (any field can be used), but i can't access to these fields.

My proposal is add a 'item' parameter on the json returned in the ajax request, and that field contains the complete object (or extra fields if the object have too many fields and not all of them are needed on the client-side) represented in the ajax request, and add a method like getItem(), which return the item selected instead of the value as the "val()" method does.

Twitter Typeahead plugin have a event ('typeahead:selected') which is fired when the user select an item, and the function of this event has two parameters, the event himself and the item with the object. Would be nice have something like that here....

this is my json proposal:

[
    {
        item: object
        value: 'string', 
        text: 'string',
        class: 'string',
        disable: false, 
        divider: true,
        data: {
            divider: true,
            subtext: 'string',
            icon: 'class-name', // Icon class name ex: icon-glass
            content: '<div class="custom-class">my value label</div>',
        }
    }
    ....
]

Would be nice too, have events like onOpen, onClose, onSelect, beforeRequest, afterRequest, etc ๐Ÿ‘

IE8 reserved word "class"

In IE8 the problem is occurring while processing the javascript because the reserved word "class". You could set it under another name to be compatible with IE8? Or fix using quotes neither the code below:

Line 536:

'class': $ option.attr ('class') || ''

Line 592, 593:

 if (item['class'].length) {
   $option.attr('class', item['class']);
}

Line 1010:

'class': '',

plugin.lastRequest.jqXHR.abort() never reached

Hi there and thank you for this wonderful plugin!

However, I have found a small flaw:

While you have planned for previous requests to be aborted when a new one is created, your implementation does not work because you store the last request only on completion (in the always() handler).

Therefore, if it's still running when the next request is created, it is not aborted because it has not yet been stored in plugin.lastRequest.

Thanks,

Christophe

Selected Items and Multiple Select Search

First of all, thanks for this amazing plugin.
I have some problems here, I hope that someone can help me.

The class "selected" in each selected li doesn't appear. I mean, every time I selected some items the LI elements become the same, and I don't know each one I really selected.

One more thing, think about my situation:
I search something and selected some items, then I do another search to continue my selection when returns the data the old values that I was selected disapears.
The problem is that I need do some searches to complete my selection, I don't want to select just the data of one search.

HTML

<select id="test" title="All" data-selected-text-format="count" class="selectpicker form-control" multiple="multiple" data-live-search="true">
    <option value="" data-hidden="true"></option>
</select>

JS

$('.selectpicker').selectpicker();

$('#test').ajaxSelectPicker({
    ajaxResultsPreHook: function(data){
        var arr = [];
    if(data.length){
            for(var i = 0; i < data.length; i++){
                arr.push({
                    text: data[i].name,
                    value: data[i].id
                });
            }
    }
    return arr;
    },
    ajaxSearchUrl: 'google.com', //example
    ajaxOptions: {
        type: 'GET',
        dataType: 'jsonp',
        data: {
            search: '{{{q}}}'
        }
    }
});

Thanksss!

preserveSelected and multiple select

With preserveSelected set to true, a multiple select becomes unusable. Once an option is selected it goes into the currently selected group, but all other options are removed from the list.

If said option is then unselected there are no options available at all.

Select to allow free entry with an option

Hi Adam,

thks for the plugin which I am enjoying and adding in one project. I am using it with the ajax-picker addition to improve performance. Would there be any ways to allow users to enter free text (their own text) if not fund in the list? Long term addition as an option would be great but a short term hack would be welcomed. Thks and hello from France.

Stan

Is it possible to populate data without search?

I am using bootstrap-select and I don't need searchbox to be fetched data. Data should be loaded on document.ready() and should work in the same manner like bootstrap-select.

I checked your code if we can disable search and get the data on load. But I couldn't find any.

Can you please let me know if it's possible somehow?

Sample Script:

var options = {
                ajax          : {
                    url     : 'https://crossorigin.me/https://teckstack.com/wp-json/wp/v2/posts',
                    type    : 'GET'
                },
                log           : 3,
                preprocessData: function (data) {
                    var i, l = data.length, array = [];
                    if (l) {
                        for (i = 0; i < l; i++) {
                            array.push($.extend(true, data[i], {
                                text : data[i].id,
                                value: data[i].title.rendered,
                                data : {
                                    subtext: data[i].title.rendered
                                }
                            }));
                        }
                    }
                    // You must always return a valid array when processing data. The
                    // data argument passed is a clone and cannot be modified directly.
                    //return array;
                }
            };
            $('.selectpicker').selectpicker({
                liveSearch: false
            }).filter('.with-ajax').ajaxSelectPicker(options);
            $('select').trigger('change');

Thanks.

Best way to clear Currently Selected?

I've read through the code but unsure what the best approach is to programmatically clear the Currently Selected options (effectively reset the plugin).

I can't set preserveSelected = false because I do need to retain selected options between searches. But once the form is submitted (via Ajax) I need to reset everything.

I suspect I can use AjaxBootstrapSelectList.prototype.replaceOptions with a blank value, but is that the best approach?

Autocorrect

I did not found a good way to disable

autocorrect="off" autocapitalize="off" spellcheck="false"

any advise ?

TypeError: Cannot read property 'log' of undefined

Uncought exception occurs in 359 line in ajax-bootstrap-select.js

Usage:

$('.model-picker').each(function () { $(this).ajaxSelectPicker({ ajaxOptions: { url: null, data: {pattern: '{{{q}}}'}, dataType: 'json', type: 'GET' }, emptyRequest: true, }); });

Selected item disappears while searching

Hi again,

When an item is currently selected, an the user is starting a new search, the currently selected item disappears, firing any triggers bound to the 'change' event when in effect, no change has happened yet (i.e. no new selection has occurred).
Also, when the user does not select a new item, but cancels out of the dropdown, the select loses its selected item.

While this behaviour is understandable, as the selected item is not a match for the new filter, I think it would be nice to have an option to keep the selected item in the dropdown as long as no other is actively selected.

Cheers,

Christophe

Pass content from another Select

Hey,

Following my post a few days ago (#34), I've expanded my form a bit more now, so it now includes the venue. As a rule of thumb, this should be the venue of the home team, but with the option to change if necessary (for example, a cup final).

So I've set a change request set to the home team that adds the relevant venue in to the venue select box. For the most part, this is working, and it does actually add the option value in correctly. It just doesn't visually display the change. I've tried instantiating ajaxSelectPicker like you suggested, and refreshing/re-rendering the selectpicker, but I'm drawing blanks.

$('#home_team1').change(add_venue);

function add_venue()
  {
    var option = $(this).find(':selected').val(),
    dataString = "option="+option;
    if(option != '')
    {
        $.ajax({
            type     : 'GET',
            url      : 'ajax.php',
            data     : dataString,
            dataType : 'JSON',
            cache: false,
            success  : function(data) {            
                var output = '';

                $.each(data.data, function(i,s){
                    var newOption = s;

                    output += '<option value="' + newOption["team_home_venue"] + '">' + newOption["venue_name"] + '</option>';
                });

                $('#venue1').empty().append(output);
            },
            error: function(){
                console.log("Ajax failed");
            }
        }); 
    }
    $('#venue1').selectpicker('refresh').selectpicker('render').ajaxSelectPicker();
}

Is there any way to completely re-render the select based on what would be perceived to be it's existing options, or am I simply asking too much from the extension? Alternatively, there may be a better way of doing this, although I've been through both sets of documentation and I'm struggling to find a way

Not working with select multiple

Love this extension to bootstrap-select!

I've come across a use-case issue (not technically a bug) when dealing with select multiples. I want to be able to search against 3 or 4 different strings and select from each of the results. This might yield a selection from first ajax call, 2 selections from the 3rd ajax call and a final selection from a 4th ajax call.

The problem I'm having is that when results are returned all current options seem to be removed, so any selected options are removed as well. I understand that this is the default behaviour, and makes sense, so I'm wondering if it would be possible to include a plugin option to offer choice of overriding all current options with new results, or only overriding non-selected ones?

On select all selected is everything including dividers

When I click on "Select All" everything including divider is selected.

Without anything selected:
snimek z 2015-12-22 17-57-29

"Select All":
snimek z 2015-12-22 17-57-40
(" , " on the begining)

Manually selected all:
snimek z 2015-12-22 17-57-50

JSON data from server

[{"Divider": "true"}, {"Class": "1.A", "Username": "mdobrovolny1", "ID": 1, "Divider": "false", "Name": "Michal Dobrovoln\u00fd"}, {"Class": "1.A", "Username": "fdobrovolny1", "ID": 2, "Divider": "false", "Name": "Filip Dobrovoln\u00fd"}, {"Divider": "true"}, {"Class": "4.G", "Username": "fdobrovolny1", "ID": 2, "Divider": "false", "Name": "Filip Dobrovoln\u00fd"}, {"Class": "4.G", "Username": "mnetolicky1", "ID": 4, "Divider": "false", "Name": "Michal Netolick\u00fd"}]

Value of Select list:

$("#id_students").val() = ["", "1", "2", "4"]

Settings:

var options_students = {
  ajax: {
      url: Urls['ajax_classes:listClassesStudents'](),
      type: 'POST',
      dataType: 'json',
      data: {
          q: '{{{q}}}',
          classes: JSON.stringify($("#id_classes").val()),
      }
  },
  langCode: 'cs',
  log: 3,
  emptyRequest: true,
  preprocessData: function (data) {
      var i, l = data.length, array = [];
      if (l) {
          for(i = 0; i < l; i++){
              if (data[i].Divider == "true") {
                  array.push($.extend(true, data[i], {
                      divider: true,
                      data: {
                      }
                  }));
              } else {
                  array.push($.extend(true, data[i], {
                      text: data[i].Name,
                      value: data[i].ID,
                      data: {
                          subtext: data[i].Class + " - " + data[i].Username,
                      }
                  }));
              }
          }
      }
      return array;
    }
};

HTML:

<select aria-describedby="students_help" name="students" id="id_students" data-actions-box="true" data-live-search="true" multiple class="selectpicker form-control with-ajax-students"></select>

Custom source function

is there a way to provide a custom source function, at the moment, the $.ajax call is hardcoded into the plugin, how can i make it a parameter or something. cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.