How to select by Value/Text in ddSlick

ddSlick is a free light weight jQuery plugin that allows you to create a custom drop down with images and description.

Recently in some projects I had to use ddSlick. While using I faced a huge problem,

How to make a option selected by option value or it's text dynamically using jQuery?

For a normal <select> we can select them by using a normal jQuery function. But ddSlick doesn't work like this way. I've searched their documentation for this kind of function. But I found that they only gave a option select option using index number.

To solve the issue, I made a small jQuery function by which we can make any options as selected by it's text or value.

Select by Value:

//the value for which we are searching
var searchBy = 'a-value';

//#aSelectBox is the id of ddSlick selectbox
$('#aSelectBox li').each(function( index ) {

  //traverse all the options and get the value of current item
  var curValue = $( this ).find('.dd-option-value').val();

  //check if the value is matching with the searching value
  if(curValue == searchBy)
  {
      //if found then use the current index number to make selected    
      $('#aSelectBox').ddslick('select', {index: $(this).index()});
  }
});

Select by Text:

If we want to select options by it's text not value then, we can use this code,

//the text for which we are searching
var searchBy = 'a-text';

//#aSelectBox is the id of ddSlick selectbox
$('#aSelectBox li').each(function( index ) {

  //traverse all the options to get the text of current item 
  var curValue = $( this ).find('.dd-option-text').text();

  //trimming the value to remove unwanted whitespaces
  curValue = curValue.trim()

  //check if the value is matching with the searching value
  if(curValue == searchBy)
  {
      //if found then use the current index number to make selected    
      $('#aSelectBox').ddslick('select', {index: $(this).index()});
  }

});

I hope these solutions will help anyone to use ddSlick in more comfortable way.

comments powered by Disqus