Feature-rich (Dual) List Box Plugin With jQuery - jqListbox

File Size: 176 KB
Views Total: 4338
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Feature-rich (Dual) List Box Plugin With jQuery - jqListbox

jqlistbox is a powerful jQuery plugin used to render a dynamic list box from a JavaScript array containing any kind of items. With the help of built-in methods, you're able to insert/update/remove/moveup/movedown items and even to move selected items between list boxes.

How to use it:

1. The plugin requires the latest version of jQuery library has been properly loaded in the document.

<script src="/path/to/jquery.min.js"></script>
<script src="jqListbox.plugin.js"></script>

2. Create a container element for the list box.

<ul id="example">
</ul>

3. Store your data in a JavaScript array as shown below. The jqListbox plugin will always interact on this data set when you're inserting, updating, moving, etc.

var myData = [
    {'title': 'Title field 1', 'price': 1000},
    {'title': 'Title field 2', 'price': 2000},
    {'title': 'Title field 3', 'price': 3000},
    {'title': 'Title field 4', 'price': 4000},
    {'title': 'Title field 5', 'price': 1000},
    {'title': 'Title field 6', 'price': 2000},
    {'title': 'Title field 7', 'price': 3000},
    {'title': 'Title field 8', 'price': 4000}
    ...
]

4. initialize the plugin and define your own function to render the internal array as you want. Your renderer function will be called with every time in the internal array and you can return a string or a jQuery object.

$('#example').jqListbox({
  initialValues: myData
  itemRenderer: function (item) {
      return '<li>' + item.title + '</li>';
  }
});

5. You can define your own function to encode the internal array as you want. Typically you will call JSON.stringify() on your items and set its result in a hidden input so you can post it to your backend application.

$('#example').jqListbox({
  listboxValueEncoder: function (items) {
    return JSON.stringify(items);
  }
});

6. All default configuration options.

$('#example').jqListbox({

  /**
   * jQuery compatible selector string to define which elements should be treated as list items in the listbox.
   *
   * @memberOf jqListbox.options
   * @default
   * @type {string}
   */
  itemSelector: 'li',

  /**
   * jQuery compatible selector string to define which element should be used to set the value to.
   * By default the value will be a JSON encoded string.
   *
   * @memberOf jqListbox.options
   * @default
   * @type {string}
   */
  targetInput: '#listbox-value',

  /**
   * Initial values to populate the listbox from.
   * The value must be a JS array.
   *
   * @memberOf jqListbox.options
   * @default
   * @type {Array|boolean}
   */
  initialValues: false,

  /**
   * Initial encoded values to populate the listbox from.
   * Use it to set the initial values from encoded (rendered) value without the need of a targetInput.
   *
   * @memberOf jqListbox.options
   * @default
   * @type {string|boolean}
   */
  initialEncodedValues: false,

  /**
   * CSS class used to mark selected items in the listbox.
   * This option can be used on most of the cases. For more complex item logic use the itemRenderer
   * and set selectedClass to false.
   *
   * @memberOf jqListbox.options
   * @default
   * @type {string|boolean}
   */
  selectedClass: 'selected',

  /**
   * If true then a simple click event handler will be added to your rendered list items.
   *
   * @memberOf jqListbox.options
   * @default
   * @type {string|boolean}
   */
  autoSelectOnClick: true,

  /**
   * If true then multiple selection is enabled in the listbox
   *
   * @memberOf jqListbox.options
   * @default
   * @type {boolean}
   */
  multiselect: true,

  /**
   * Function called when an item is rendered.
   * By default this returning a list item (<li>) containing your raw item Object.
   * You can override this function to render your item.
   *
   * @memberOf jqListbox.options
   * @method
   * @param {Object} item The item to be rendered
   * @param {int} pos The position of the item
   * @param {jqListbox} jqListbox The jqListbox instance
   * @default
   * @type {function}
   */
  itemRenderer: function (item, pos, jqListbox) {
      return '<li>' + item + '</li>';
  },

  /**
   * Function called when the final value of the listbox is rendered (for example when the value of a
   * target hidden input is set).
   * By default this returning the JSON stringified value of your items (array).
   *
   * @memberOf jqListbox.options
   * @method
   * @param {Array} items The items to be encoded
   * @default
   * @type {function}
   */
  listboxValueEncoder: function (items) {
      return JSON.stringify(items);
  },

  /**
   * Function called when decoding is needed from the rendered values. This function is typically
   * invoked if the target input has the encoded values upon initialization.
   *
   * @memberOf jqListbox.options
   * @method
   * @param {string} values The encoded values to be decoded
   * @default
   * @type {function}
   */
  listboxValueDecoder: function (values) {
      if (values.length > 0) {
          return JSON.parse(values);
      }
      return [];
  }

});

7. Optional callback functions.

$('#example').jqListbox({

/**
* Optional callback function called before the initialization step.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeInit: false,
/**
* Optional callback function called after the initialization step.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onAfterInit: false,
/**
* Optional callback function called before a new element is inserted to the listbox via the
* insert method. Return false from this function to avoid the insertion if the new item.
* You can modify the items in this callback by returning the new array of items.
* Multi insert will call this function only once not per-item!
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {Array} items The new item(s) to be inserted. Single element array on simmple insert() and multi element array on multiInsert()
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeItemInsert: false,
/**
* Optional callback function called after a new element is inserted to the listbox via the
* insert method.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {Array} items The new item(s) inserted. Single element array on simmple insert() and multi element array on multiInsert()
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onAfterItemInsert: false,
/**
* Optional callback function called before an element is updated in the listbox via the
* update method. Return a new array from this function to change the updated elements.
* Return false from this function to avoid the update.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {Array} items The selected item(s)
* @param {Array} updateTo Array of updated items
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeItemUpdate: false,
/**
* Optional callback function called after an element is updated in the listbox via the
* update method.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {Array} item The selected item(s)
* @param {Array} updatedTo Array of updated items
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onAfterItemUpdate: false,
/**
* Optional callback function called before an element is removed from the listbox via the
* remove method. Return false from this function to avoid the deletion.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {Array} items The selected item(s)
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeItemRemove: false,
/**
* Optional callback function called after an element is removed from the listbox via the
* remove method.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {Array} items The selected item(s)
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onAfterItemRemove: false,
/**
* Optional callback function called before the listbox is cleared via the
* clear method. Return false from this function to avoid the clearing.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeClear: false,
/**
* Optional callback function called after the listbox has cleared via the clear method.
*
* @method
* @default false
* @this {jQuery} The container jQuery element
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onAfterClear: false,
/**
* Optional function called after any change in the items but before any rendering functions.
* This function can be used to implement custom sorting, filtering, etc before rendering take effect.
*
* @method onAfterDataChanged
* @default false
* @this {jQuery} The container jQuery element
* @param {array} itemsData Array of objects containing the item in the "item" property and the "isSelected" flag. The same structure must be returned.
* @param {string} event The name of the event: insert, update, remove, clear, movedown or moveup.
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onAfterDataChanged: false,
/**
* Optional function called after any change in the items.
* This function will be called after insert, update, remove, clear, movedown and moveup.
* The change event will be passed as parameter.
*
* @method onChanged
* @default false
* @this {jQuery} The container jQuery element
* @param {string} event The name of the event: insert, update, remove, clear, movedown or moveup.
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onChanged: false,
/**
* Optional function called before the actual selection has been made.
* Return false form your function to avoid selection.
*
* @method onBeforeSelect
* @default false
* @this {jQuery} The container jQuery element
* @param {int} The position of the element to be selected
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeSelect: false,
/**
* Optional function called before the actual deselection has been made.
* Return false form your function to avoid selection.
*
* @method onBeforeSelect
* @default false
* @this {jQuery} The container jQuery element
* @param {int} The position of the element to be selected
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeDeSelect: false,
/**
* Optional function called before the render step.
* Return false form your function to avoid rendering logic.
*
* @method onBeforeRender
* @default false
* @this {jQuery} The container jQuery element
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onBeforeRender: false,
/**
* Optional function called after the render step.
*
* @method onAfterRender
* @default false
* @this {jQuery} The container jQuery element
* @param {jqListbox} jqListbox The jqListbox instance
* @type {boolean|function}
*/
onAfterRender: false

});

8. API methods.

var myListBox = $('#example').jqListbox();

// Inserts a new element to the end of the listbox
$myListBox.jqListbox('insert', item);

// Inserts a new element at the specified position
$myListBox.jqListbox('insertAt', item, position);

// Inserts new elements from the array to the end of the listbox
$myListBox.jqListbox('insertMulti', items);

// Inserts new elements from the array to the specified position of the listbox
$myListBox.jqListbox('insertMultiAt', items, position);

// Updates the currently selected element(s) with the new data.
// If multiple items are selected then all of them will be updated.
$myListBox.jqListbox('update', updateitem);

// Updates all of the currently selected element with the new datas
// updatedItems should have the same number of element as the currently selected elements
// Selected elements will be updated one-by-one with the data in the updatedItems
$myListBox.jqListbox('updateMulti', updateitems);

// Updates the element in position
$myListBox.jqListbox('updateAt', updateitem, position);

// Removes all of the currently selected items.
$myListBox.jqListbox('remove');

// Removes the element in position.
$myListBox.jqListbox('removeByIndex', position);

// Clears the listbox
$myListBox.jqListbox('clear');

// Move up all of the currently selected items.
$myListBox.jqListbox('moveup');

// Move up the item by position.
$myListBox.jqListbox('moveupByIndex', position);

// Move down all of the currently selected items.
$myListBox.jqListbox('movedown');

// Move down the item by position.
$myListBox.jqListbox('movedownByIndex', position);

// Switches the positions of two elements. This method won't trigger the render() method!
$myListBox.jqListbox('switchElements', pos1, pos2);

// Shift every elements up (left) in the array. This method won't trigger the render() method!
$myListBox.jqListbox('shiftElementsUp');
 
// Shift every elements down (right) in the array. This method won't trigger the render() method!
$myListBox.jqListbox('shiftElementsDown');

// Transfer selected elements to another jqListbox.
// The two jqListbox should contain the same type of elements because this method will call the other listbox's insert method.
$myListBox.jqListbox('transferSelectedTo', listbox, copy);

// Transfer the item by index to another jqListbox.
// The two jqListbox should contain the same type of elements because this method will call the other listbox's insert method.
$myListBox.jqListbox('transferByIndexTo', listbox, index, copy);

// Transfer multiple items by index to another jqListbox.
// The two jqListbox should contain the same type of elements because this method will call the other listbox's insert method.
$myListBox.jqListbox('transferByIndexMultiTo', listbox, indices, copy);

// Returns the rendered (encoded) target value
$myListBox.jqListbox('getTargetValue');

// Returns all of the currently stored elements as array
$myListBox.jqListbox('getAsArray');

// Sets the listbox items from an array. This will overwrite any currently stored elements.
$myListBox.jqListbox('setFromArray', newItems);

// Sets the listbox items from an the target value. This will overwrite any currently stored elements.
$myListBox.jqListbox('setFromTargetValue', data);

// Returns the number of elements in the listbox
$myListBox.jqListbox('count');

// Returns the number of selected elements in the listbox
$myListBox.jqListbox('countSelected');

// Selects an element by index
$myListBox.jqListbox('select', position);

// Deselects the element by index if it is selected
$myListBox.jqListbox('deselect', position);

// Select all elements
$myListBox.jqListbox('selectAll');

// Deselects any selected element
$myListBox.jqListbox('deselectAll');

// Returns an array of the selected elements
$myListBox.jqListbox('getSelected');

// Returns true if the item in position is selected
$myListBox.jqListbox('isSelected');

// Returns all selected elements
$myListBox.jqListbox('getSelectedItems');

// Returns a jQuery object with the elements of selected listbox items
$myListBox.jqListbox('getSelectedJQueryItems');

// Returns the jQuery element by position
$myListBox.jqListbox('getJQueryItemByIndex', pos);

// Re-render all of the items in the listbox
$myListBox.jqListbox('render');

// Calls the passed callback on every items.
// Your custom callback function will get the following parameters:
// item object, item position, jquery item, jqListbox instance
// Scope: the jQuery element which has the jqListbox initialized
$myListBox.jqListbox('itemWalk', fn);

// Calls the passed callback on every selected items.
// Your custom callback function will get the following parameters:
// item object, item position, jquery item, jqListbox instance
// Scope: the jQuery element which has the jqListbox initialized
$myListBox.jqListbox('selectedWalk', fn);

Change log:

2017-12-02

  • Added onBeforeSelect, onBeforeDeselect, removed JSDoc, updated manual

2017-09-25

  • Added: onAfterDataChanged event

2017-08-12

  • Check with latest jQuery

This awesome jQuery plugin is developed by ferencb. For more Advanced Usages, please check the demo page or visit the official website.