Sunday, February 4, 2018

Some Tips and Tricks of Working With Bootstrap Select2 Control

Hello,

Since I am a web developer, I used to work  a lot with Bootstrap Select 2 Control. Here I am going to share some quick tips and tricks of working with Select 2 controls.

1) Dynamically create Select2 control with JavaScript

When we are working on dynamic websites, sometimes we also have to create select2 controls dynamically. Most of the developers faces issues here. Because select2 control is created by JavaScript on document ready. So if you want create it dynamically, first append basic html of control inside and the by using JavaScript init it.

Something like this.

$('.select2').select2();

Sometimes it takes time to get reflect in DOM so in this case you may have to give some timeout.

setTimeout(function(){
      $('.select2').select2();
},500);

2) Open Select2 dropdown on focus.

This is one more UX experience. Most of the web users are used to work with TAB. So in your form if you have select2 control and you come on it via tab. It should open dropdown.

Here is how we can do it.

$(document).on('focus', '.select2', function() {
if($(this).prev().val() == ''){
  $(this).siblings('select').select2('open');
}
});

3) Open Select2 dropdown with down arrow key

This is one more UX experience. Most of the web users are used to work with up and down arrow while working with dropdown. So in case of select2 they are expecting the same result.

$(document).on('keydown', '.select2', function(event) {
    if(event.keyCode == 40){
    $(this).siblings('select').select2('open');
    }
});

4) Keep focus on Select2 after selecting item and dropdown is closed.

In new version of Select2 there is a bug that after you select an item and dropdown is closed. It will lost focus. So to keep focus on the control, use following code.

$('select').on(
  'select2:close',
  function () {
  $(this).focus();
  }
  );
},1000);

Hope this tips helps you in your development with Select2.

No comments:

Post a Comment