js/jqListbox.plugin-1.3.js
file to your web root (or in a subfolder)div
) which will contain your list
container element.
ul
list under a
div
element
you can style your div
as fixed height and overflow: auto
to
imitate a listbox with scroll.
ul
) which will contain your list
items.
.jqListbox()
on the element containing your list items. When a
new item will be appended
it will be appended into your container element. Don't confuse the optional wrapper element
created for styling and the container element containing your list items!
ul
list you must call .jqListbox
on the
ul
element: $('ul#myul').jqListbox();
li
).
Items will be matched with the defined itemSelector
relative to your container element
like
$('ul#myul').find(itemSelector);
.jqListbox()
on your container element after jQuery and jqListbox loaded
and the DOM is ready
Container: the main container for all of your items. If you are using a list
then the container can be the <ul>
element.
You must call .jqListbox()
on your container element.
Wrapper: an optional element containing your container element mainly because of styling via CSS.
Item: one of your item in your listbox.
listboxValueEncoder: a function which will be called any time your listbox has
changed (insert, update, etc). The array of the stored items will be passed to this function. Your
function must return a value which can be used for example to post back to your backend application
and save it. It is recommended to use JSON.stringify()
listboxValueDecoder: a function which will be called when you need to decode your
elements. This function is used when the initial values is set from a value generated by the
listboxValueEncoder
.
itemRenderer: a function which will be called when your items are rendered. This function is called once for every item so you must return a string or jQuery object which must be appended to your list container element.
JSON: JavaScript Object Notation. Text representation of JavaScript objects. Read more here and here.
This plugin needs jQuery 1.x (tested with 1.11.3), 2.x (tested with 2.1.4) or 3.x (tested with 3.2.1). You can download jQuery from here or you can use the jQuery CDN. You must include jQuery on every page where jqListbox is used.
Once jQuery is included you must include jqListbox after jQuery is loaded.
For production sites you should use the minified version of the plugin (filename ends with
.min.js
).
<!-- If the plugin found in your /js folder --> <script type="text/javascript" src="js/jqListbox.plugin-1.3.min.js"></script>
No specific style sheet is needed for the jqListbox plugin. Also no style sheets are included in the package.
You can use this plugin with your own CSS styles.
You can use any structure you like! Just ensure that your items are wrapped under a container.
You will need a container which holds your items. You can initialize the plugin on this container. Also typically you will need to declare when and how to insert, update, remove and render items.
Item selector must be defined relative to your container element because it will be matched
with $(container).find(itemSelector);
when needed!
The default itemSelector is li
.
You can override this option via the option itemSelector
.
In the following example your container element will be ul#customlist
while your
items will be the li
tags.
<!-- HTML structure --> <ul id="customlist"> </ul> ... <!-- somewhere in your JS code --> <script> $('#customlist').jqListbox(); </script>
Simply call the plugin jqListbox()
on your container element. You can define custom
options as a passed parameter object.
<script> $('#customlist').jqListbox({ selectedClass: 'selected-item', mutliselect: false }); </script>
ul
and li
tags wrapped under a container div
. Watch out for comments and
descriptions. Check the inline documentation in the source file for reference!
<!-- HTML structure --> <ul id="customlist"> </ul> ... <!-- somewhere in your JS code --> <script> $('#customlist').jqListbox(); </script>
The itemRenderer
function defines how an item is rendered. The default is to render li
items
from a basic Array of string
structure (var items = ['Item','Item',...];
).
The itemRenderer
function will be called every time a rendering is needed. The actual
rendered item, its position and the instance of the current jqListbox will be passed as parameters.
In this example we are assuming that your items are Objects which contains a field
and a
price
property which needs to be rendered.
<script> $('#customlist').jqListbox({ // Render items itemRenderer: function(item, pos, listbox) { return '<li>' + item.title + ' (' + item.price + ')</li>'; } }); </script>
The listboxValueEncoder
function produces the result of your listbox (remember the image
on the top of the documentation).
jqListbox supporting setting this value in an input by default (see option targetInput
) but
it is up to you what to do with this value. Typically you want to post it back to your backend
application to save it.
The default function used by jqListbox is to convert your array of items to a JSON string. Typically
this is what you need: encode your values to JSON string - later you can decode this string on
backend side if needed (json_decode
in PHP) to save in DB for example.
If you need something else then JSON.stringify()
for encoding the values of your listbox
just fire up your own function via the option listboxValueEncoder
.
By default jqListbox will try to set this value in an input with id #listbox-value
.
You can override this selector with the option targetInput
. Set the value of this option
to false
to completely disable this functionality and do it on your own.
Now for the example we will modify the targetInput
selector to point to our newly created
hidden input. We must add a dummy form above our ul
list.
<!-- HTML structure --> <form id="target-form" method="post" action="/post.php"> <input type="hidden" name="output" id="output"> </form> <ul id="customlist"> </ul> ... <script> $('#customlist').jqListbox({ // Render items itemRenderer: function(item, pos, listbox) { return '<li>' + item.title + ' (' + item.price + ')</li>'; }, // Modify the input selector targetInput: '#output' }); </script>
If you need custom output logic
The onAfterRender
event will be triggered any time when the listbox has changed and
re-rendered
so it is good to put new output rendering logic there. Don't forget to disable the
targetInput
option if you need custom logic! Check out the options below.
A decoder is needed if you want to initialize/pre-set elements in your listbox from encoded values.
Generally the listboxValueDecoder
function is the opposite function of the listboxValueEncoder
.
The default value of the listboxValueDecoder
is a function which calls the JSON.parse()
,
the opposite of JSON.stringify()
- so it will return the original array of your items.
If you remember we are already using the default function of listboxValueEncoder
so we are
good
to also leave the default option for listboxValueEncoder
for now.
For inserting, updating, deleting your elements you should add some action buttons. You must define your own logic for this actions and call jqListbox's methods to handle your items.
For this example we are creating a button and add a new item on click.
<a href="#" id="insert">Insert new element</a> <script> $('#insert').click(function(e){ // Show your own dialog or something to your user // and clicking on some button insert the new element // For this demo we just inserting a new element // So basically yes, this call to the insert method should go to the submit handler of your form for example $('#customlist').jqListbox('insert', {'title' : 'New element', 'price' : 12345}); e.preventDefault(); return false; }); </script>
Updating is similar to inserting: you must call the update
method to update
the selected item.
If multiple selection is allowed and more than one element is selected then you can update
all of them with the same data or pass an array of updated elements to update each selected
element with different data (so you must pass one updated element for every selected element) to the
updateMulti
method. Yes, there are two update methods: the update
and the
updateMulti
(and the third is the updateAt
).
<a href="#" id="update">Update element</a> <script> $('#insert').click(function(e){ // Show your own dialog or something to your user // and clicking on some button update the selected element(s) // For this demo we just updating the selected elements $('#customlist').jqListbox('update', {'title' : 'Updated element', 'price' : 99999}); e.preventDefault(); return false; }); </script>
Also deletion is similar to updating. Calling the remove
method will remove
all of the selected elements.
<a href="#" id="remove">Remove selected</a> <script> $('#remove').click(function(e){ if (confirm('Are you sure?')) { $('#customlist').jqListbox('remove'); } e.preventDefault(); return false; }); </script>
Calling the clear
method will remove all of the elements.
<a href="#" id="clear">Clear</a> <script> $('#clear').click(function(e){ if (confirm('Are you sure?')) { $('#customlist').jqListbox('clear'); } e.preventDefault(); return false; }); </script>
The built-in moveup
method supports multiple selection.
When calling moveup
all of the selected items will be moved up by one position.
If the very-first element is moved up it will be moved to the end of the list and all other elements
will be pushed up by one position.
<a href="#" id="moveup">Move up</a> <script> $('#moveup').click(function(e){ $('#customlist').jqListbox('moveup'); e.preventDefault(); return false; }); </script>
The built-in movedown
method supports multiple selection.
When calling movedown
all of the selected items will be moved down by one position.
If the very-last element is moved down it will be moved to the beginning of the list and all other
elements
will be pushed down by one position.
<a href="#" id="movedown">Move up</a> <script> $('#movedown').click(function(e){ $('#customlist').jqListbox('movedown'); e.preventDefault(); return false; }); </script>
Of course you don't want to enable the update or remove action if no items are selected. You can easily do this by setting up some easy logic.
The onBeforeRender
or the onAfterRender
are two good candidates for
this kind of logics.
What you want is: if no element is selected (countSelected()
method returns 0) then
disable the update,remove,moveup and movedown actions. In this example we just add a disabled class
to these buttons.
<script> $('#customlist').jqListbox({ ... onBeforeRender: function (listbox) { if (listbox.countSelected() == 0) { $('#update,#remove,#moveup,#movedown').addClass('disabled'); } else { $('#update,#remove,#moveup,#movedown').removeClass('disabled'); } } ... }); </script>
There are a lot of callbacks triggered by different events: for example you can fire up some custom logic before a new element is inserted or elements are updated. Also you can change the newly inserted element before the insertion, etc. There are a lot of possibilities in these callbacks!
You can use the following methods in jqListbox.
Every method can be accessed via the jqListbox instance but there are some methods which are
intended for internal use only - for example you won't need to call setupAutoClickHandler by hand.
I'm listing only the methods intended for use in your code - however you can check all of the methods
in the documented source file.
Call these methods on the jqListbox instance on your element like $('#customlist').jqListbox('remove');
.
Simply pass parameters like $('#customlist').jqListbox('removeByIndex', 4);
. In the
callbacks where the
current instance is passed you can simply use the methods of the passed instance (like listbox.removeByIndex(4);
Method | Description | Parameters | Returns |
---|---|---|---|
count | Returns the number of elements in the listbox. | - |
int - the length of the listbox
|
countSelected | Returns the number of selected elements in the listbox. | - |
int
|
reset | Resets the listbox: clear, initialize items based on the options and renders the initial state. | - | - |
render | Renders the listbox (items) and the output value. | - | - |
insert | Inserts a new item at the end of the listbox. |
item - the new item
|
int - the new length of the listbox
|
insertAt | Inserts a new item at the given position. Negative value means counting for the end (0 means first position, -1 means last position). |
item - the new item
position - the position
|
int - the new length of the listbox
|
insertMulti | Inserts multiple items at the end of the listbox |
items - array of new items
|
int - the new length of the listbox
|
insertMultiAt | Inserts multiple items at the given position. Negative value means counting for the end (0 means first position, -1 means last position). |
items - array of new items
position - the position
|
int - the new length of the listbox
|
update | Updates the selected element(s). If multiple elements are selected then all of the elements will be updated with the passed data. |
updatedItem - data (Object) of the new item
|
int - the number of the selected items
|
updateMulti | Updates the selected element(s). You must pass as many updated items as many items are selected: each of them will be updated with the next item in the array (0-0, 1-1, etc.) |
updatedItems - array of new items
|
int - the number of the selected items
|
updateAt | Updated the item in the given position. Negative value means counting for the end (0 means first position, -1 means last position). |
updatedItem - the new item
position - the position
|
Object - the updated item data
|
remove | Removes all of the selected items | - |
int - the new length of the listbox
|
removeByIndex | Removes an item in the given position. |
position - the position
|
int - the new length of the listbox
|
clear | Removes all items | - | - |
moveup | Moves up selected items by one position. | - | - |
moveupByIndex | Moves up the item in position by one. |
position - the position
|
- |
movedown | Moved down selected items by one position. | - | - |
movedownByIndex | Moved down the item in position by one. |
position - the position
|
- |
switchElements | Switches to elements by position. |
pos1 - the position
pos2 - the position
|
- |
shiftElementsUp | Shift every elements by one position up | - | - |
shiftElementsDown | Shift every elements by one position down | - | - |
transferSelectedTo | Transfer the currently selected elements to another jqListbox instance. |
listbox - the another container of the jqListbox instance. This must be the
jQuery element for example $('#anotherlistbox') .
copy - optional. Set this parameter to true if you want to
copy the elements instead of move (transfer).
|
- |
transferByIndexTo | Transfer one element in the given position to another jqListbox instance. |
listbox - the another container of the jqListbox instance. This must be the
jQuery element for example $('#anotherlistbox') .
index - the index of the element to copy/move.
copy - optional. Set this parameter to true if you want to
copy the element instead of move (transfer).
|
- |
transferByIndexMultiTo | Transfer multiple elements by position to another jqListbox instance. |
listbox - the another container of the jqListbox instance. This must be the
jQuery element for example $('#anotherlistbox') .
indices - the array of indices of the elements to copy/move.
copy - optional. Set this parameter to true if you want to
copy the elements instead of move (transfer).
|
- |
getItemByIndex | Returns the item in position. Range checks must be done by you! |
pos - the position
|
Object |
getTargetValue |
Returns the target (encoded) value of the listbox by calling listboxValueEncoder
and
returning its return value.
|
- |
string|Object - the return value of the listboxValueEncoder function
|
setFromTargetValue |
Overwrite the current internally stored array from the passed encoded value by calling the
listboxValueDecoder function.
|
data
|
int - the new length of the listbox
|
getAsArray | Returns the internally stored array of the items. | - |
Array
|
setFromArray | Overwrite the current internally stored array with the provided new one. Render and other methods won't be called. |
newItems - the array of the new items
|
int - the new length of the listbox
|
select | Selects the element in the given position. |
position - the position
|
- |
deselect | Deselects the element in the given position if it is selected. |
position - the position
|
- |
selectAll | Selects all elements in the listbox. | - | - |
deselect | Deselects any selected elements. | - | - |
getSelected | Returns the array of the positions of the selected elements. | - |
Array
|
isSelected | Returns true if the element in the given position is selected. |
position - the position
|
jboolean
|
getSelectedItems | Returns the array of the selected elements. | - |
Array
|
getSelectedJQueryItems | Returns the jQuery collection of the selected elements. | - |
jQuery
|
getJQueryItemByIndex | Returns the jQuery item in the given position. |
position - the position
|
jQuery
|
itemWalk |
Calls the provided function with each item one-by-one.
The current item, its position, its jQuery item and the current jqListbox instance is passed as parameters. |
fn - Function to be called
|
- |
selectedWalk |
Calls the provided function with each selected item one-by-one.
The current item, its position, its jQuery item and the current jqListbox instance is passed as parameters. |
fn - Function to be called
|
- |
You can pass several options to the jqListbox plugin on initialization.
Option | Type | Description | Default value |
---|---|---|---|
itemSelector | string |
The jQuery selector used to find your items in your list. The selector will be used as
$(container).find(itemSelector) so you must define it relative to your container.
|
li |
targetInput | string|boolean |
The jQuery selector used to find your target input (where the final value of your listbox will be set). Set this option to false to disable the automatic value setting. | #listbox-value |
initialValues | Array|boolean |
An array of your initial values to be pre-set when initializing the listbox. False by default - no initial values will be set. | false |
initialEncodedValues | string|boolean |
An array of your encoded initial values to be pre-set when initializing the listbox. This must be a string compatible with your decoder. False by default - no initial values will be set. | false |
If initialValues is false and initialEncodedValues is false then jqListbox will try to pre-set
your
values from your targetInput: if this option is not false and your input contains some encoded
elements
jqListbox will set the elements from there. So the order of this is:
initialValues > initialEncodedValues > targetInput > empty listbox
|
|||
selectedClass | string|boolean |
A class name used on selected items. jqListbox by default puts this class on your items when selecting. Set this option to false to disable this functionality. | selected |
autoSelectOnClick | boolean |
If true then items will be automatically selected on a click event.
|
true |
multiselect | boolean |
If true multiple selection is allowed. | true |
CALLBACKS | |||
itemRenderer | Function |
Function to be used when rendering items. The current rendered item, its position and the jqListbox instance is passed as parameters. You should return a string or a jQuery object from this function. |
function (item, pos, jqListbox) { return '<li>' + item + '</li>'; } |
listboxValueEncoder | Function |
Function used when rendering the output of your listbox. You should return a string from this function (which can be set in your targetInput for example. The array of items will be passed as parameter. |
function (items) { return JSON.stringify(items); } |
listboxValueDecoder | Function |
Function used when decoding output values (transforming back to array). |
function (values) { if (values.length > 0) { return JSON.parse(values); } return []; } |
onBeforeInit | Function|boolean |
Function called before initializing the jqListbox. The current jqListbox instance is passed as parameter. | false |
onAfterInit | Function|boolean |
Function called after initializing the jqListbox. The current jqListbox instance is passed as parameter. | false |
onBeforeItemInsert | Function|boolean |
Function called before an element or multiple elements are inserted to the listbox.
The to-be-inserted element(s) will be passed as an array (even if only one element is inserted).
Also the current jqListbox instance is passed as a parameter.
You can modify the to-be-inserted elements by returning a new array from this function. You can ignore the insertion by returning a boolean false from this function. |
false |
onAfterItemInsert | Function|boolean |
Function called after an element or multiple elements are inserted to the listbox. The to-be-inserted element(s) will be passed as an array (even if only one element is inserted). Also the current jqListbox instance is passed as a parameter. | false |
onBeforeItemUpdate | Function|boolean |
Function called before an element or multiple elements are updated in the listbox.
The to-be-updated element(s) will be passed as an array (even if only one element is updated).
The new (updated elements will be passed as an array. Also the current jqListbox instance is passed as a parameter. You can modify the updated elements by returning a new array from this function (so you can change the target values). You can ignore the update by returning a boolean false from this function. |
false |
onAfterItemUpdate | Function|boolean |
Function called after an element or multiple elements are updated in the listbox.
The to-be-updated element(s) will be passed as an array (even if only one element is updated). The new (updated elements will be passed as an array. Also the current jqListbox instance is passed as a parameter. |
false |
onBeforeItemRemove | Function|boolean |
Function called before an element or multiple elements are removed from the listbox.
The to-be-removed element(s) will be passed as an array (even if only one element is removed).
Also the current jqListbox instance is passed as a parameter. You can modify the list of to-be-removed elements by returning a new array from this function (so you can change the target values). You can ignore the remove by returning a boolean false from this function. |
false |
onAfterItemRemove | Function|boolean |
Function called after an element or multiple elements are removed from the listbox.
The current jqListbox instance is passed as a parameter. |
false |
onBeforeClear | Function|boolean |
Function called before the clear operation.
The current jqListbox instance is passed as a parameter. You can ignore the remove by returning a boolean false from this function. |
false |
onAfterClear | Function|boolean |
Function called after the clear operation.
The current jqListbox instance is passed as a parameter. |
false |
onAfterDataChanged | Function|boolean |
Function called after any type of change (insert, update, remove, clear, movedown, moveup and even after setFromArray and init)
but before any render happened. This way you can modify the data after it has just changed.
The array of current data will be passed as a parameter. This parameter will be an array of objects where the item property store the actual item while the isSelected property is true if the item is currently selected.
You must return the same structure (objects with item and isSelected properties).
The type of the operation will be passed as parameter. The current jqListbox instance is passed as a parameter. |
false |
onChanged | Function|boolean |
Function called after any type of change: insert, update, remove, clear, movedown or moveup.
The type of the operation will be passed as parameter. The current jqListbox instance is passed as a parameter. This method will be called always after the render operation. You can't change
the original operations here (use the onBefore... callbacks for this).
|
false |
onBeforeSelect | Function|boolean |
Function called before the select operation.
The position of the want-to-be selected item and the current jqListbox instance is passed as a parameter. Return false from this callback to ignore the whole select logic. |
false |
onBeforeDeSelect | Function|boolean |
Function called before the deselect operation.
The position of the want-to-be deselected item and the current jqListbox instance is passed as a parameter. Return false from this callback to ignore the whole deselect logic. |
false |
onBeforeRender | Function|boolean |
Function called before the render operation.
The current jqListbox instance is passed as a parameter. Return false from this callback to ignore the whole render logic. If you do this then no item and output rendering will be done. |
false |
onAfterRender | Function|boolean |
Function called after the render operation.
The current jqListbox instance is passed as a parameter. |
false |
Each callback and method uses the scope of the container element which has the jqListbox instance. It
means that $(this)
will point
to the container jQuery element inside your callback.
<script> $('#price-table').jqListbox({ onBeforeAllowed: function (el, id, jqListbox){ $(this).remove(); // this will remove the $('#price-table') element! } }); </script>