Code Monkey home page Code Monkey logo

tree-multiselect.js's Introduction

jQuery Tree Multiselect

CircleCI Coverage Status devDependency Status

This plugin allows you to add a sweet treeview frontend to a <select> node. The underlying <select> node can be used as it was before. This means you can still use $("select").val() or selectElement.value to get the value, as if there was no plugin. If you want to add options dynamically, please continue reading, there are some more steps you need to take.

  • Make sure you've got <meta charset="UTF-8"> in your <head> or some of the symbols may look strange.
  • Requires jQuery v1.8+

demo image

Demo

My website has a simple demo running.

How To Use

  1. Set the multiple="multiple" attribute on your <select>
  2. Add attributes to <option> nodes
  3. Execute $.treeMultiselect(params) with whatever params you want

Setting up your <select>

  • Make sure your <select> has the multiple attribute set.

The <option> children can have the following attributes.

Option Attributes

Option Attribute name Description
selected Have the option pre-selected. This is actually part of the HTML spec. For specified ordering of these, use data-index
readonly User cannot modify the value of the option. Option can be selected (ex. <option selected readonly ...)
data-section The section the option will be in; can be nested
data-description A description of the attribute; will be shown on the multiselect
data-index For pre-selected options, display options in this order, lowest index first. Repeated items with the same index will be shown before items with a higher index. Otherwise items will be displayed in the order of the original <select>

All of the above are optional.

Your data-section can have multiple section names, separated by the sectionDelimiter option. If you don't have a data-section on an option, the option will be on the top level (no section).

Ex. data-section="top/middle/inner" will show up as

  • top
    • middle
      • inner
        • your option

API

$.treeMultiselect(params)

Renders a tree for the given jQuery <select> nodes. params is optional.

$("select").treeMultiselect();
let params = {searchable: true};
$("select").treeMultiselect(params);
function treeOnChange(allSelectedItems, addedItems, removedItems) {
  console.log("something changed!");
}

$("select").treeMultiselect({
  allowBatchSelection: false,
  onChange: treeOnChange,
  startCollapsed: true
});
Params
Name Default Description
allowBatchSelection true Sections have checkboxes which when checked, check everything within them
collapsible true Adds collapsibility to sections
enableSelectAll false Enables selection of all or no options
selectAllText Select All Only used if enableSelectAll is active
unselectAllText Unselect All Only used if enableSelectAll is active
freeze false Disables selection/deselection of options; aka display-only
hideSidePanel false Hide the right panel showing all the selected items
maxSelections 0 A number that sets the maximum number of options that can be selected. Any positive integer is valid; anything else (such as 0 or -1) means no limit
onChange null Callback for when select is changed. Called with (allSelectedItems, addedItems, removedItems), each of which is an array of objects with the properties text, value, initialIndex, and section
onlyBatchSelection false Only sections can be checked, not individual items
sortable false Selected options can be sorted by dragging (requires jQuery UI)
searchable false Allows searching of options
searchParams ['value', 'text', 'description', 'section'] Set items to be searched. Array must contain 'value', 'text', or 'description', and/or 'section'
sectionDelimiter / Separator between sections in the select option data-section attribute
showSectionOnSelected true Show section name on the selected items
startCollapsed false Activated only if collapsible is true; sections are collapsed initially

Examples

.remove()

Removes the tree from the DOM. Leaves the original <select> intact.

let trees = $("select").treeMultiselect({searchable: true});
let firstTree = trees[0];
firstTree.remove();

.reload()

Reinitializes the tree. You can add <option> children to the original <select> and call .reload() to render the new options. User-changed selections will be saved.

let trees = $("select").treeMultiselect();
let firstTree = trees[0];

// add an option
$("select#id").append("<option value='newValue' data-section='New Section' selected='selected' data-description='New value'>New Value</option>");
firstTree.reload();

Installation

Load jquery.tree-multiselect.min.js on to your web page. The css file is optional (but recommended).

You can also use bower - bower install tree-multiselect

How to build

You need to have grunt-cli installed so you can run the grunt command.

  • Run tests: grunt or grunt test
  • Build dist JavaScript file: grunt build
  • Build Sass: grunt sass
  • Build everything: grunt release

FAQ

Help! The first element is selected when I create the tree. How do I make the first element not selected? You didn't set the multiple attribute on your <select>. This is a property of single-option select nodes - the first option is selected.

License

MIT licensed.

tree-multiselect.js's People

Contributors

patosai avatar dependabot[bot] avatar axpauls avatar wilsonge avatar

Stargazers

Thomas King avatar Mikael Gustafsson avatar Ebrar HAŞLAK avatar  avatar Paul Russo avatar  avatar  avatar  avatar Yaroslav Kasianov avatar  avatar Syan avatar YuShin avatar  avatar Chason Du Xiaocheng avatar Ralf Düsedau avatar Alper Dereli avatar  avatar Carlo Feniello avatar  avatar Davi Barros Pires avatar Andyfoo avatar Marcelo Garbin avatar DeokJung Kim avatar Алексеј avatar Juri Wolf avatar  avatar Cornel avatar Gan Yi Zhong avatar  avatar AQUN avatar Anthony-Lu avatar Furkan SAGLAM avatar Yasin avatar Zoe avatar zhazihong avatar ourenyang avatar  avatar J avatar  avatar  avatar Tao avatar O0oo0O avatar  avatar socialcast avatar 1dao avatar  avatar Iinuma Noriyuki avatar qiutian00 avatar Han Jinsong avatar  avatar  avatar Dariyousch Käther avatar wordenfan avatar Changsheng Zhu avatar  avatar Ben Booth avatar wmwyyx avatar  avatar Cappuccino avatar  avatar  avatar Frank Mayer avatar Nick Ivanov avatar RangoFu avatar Here we goal avatar Alexander Petrichkovich avatar  avatar Jan Padysak avatar cloud avatar Hao Zhan avatar  avatar Jaideep Ghosh avatar Giorgos Sarigiannidis avatar  avatar Dongkai Zhang avatar 小林 avatar  avatar Tobias Goecke (Göcke) avatar crax avatar mymbrooks avatar Markus Chiarot avatar Sam Willis avatar LeeYiFang avatar Mohamed avatar Tyler avatar  avatar Claudio Lecher avatar BinJia avatar  avatar Stempora avatar DevSaver avatar Alexandr Hanák avatar  avatar  avatar Andreas Zrost avatar  avatar Simon avatar Alexey Merezhko avatar caco avatar Vo Thanh Tung avatar

Watchers

Omar Dixon avatar Johnny avatar valamata avatar mymbrooks avatar Ryan Wu avatar Zeke avatar alexbian avatar xd avatar  avatar  avatar  avatar SachaDee avatar Daniel Clarke avatar  avatar 刘忆先 avatar liangjianyun avatar

tree-multiselect.js's Issues

default a select option is checked

Hey there,
So by default one option within the select list is checked..How do I load the tree so that none of the items are checked?

Thanks in advance

refresh option

Hi Patosai... This is a nice application... in my program first i will populate tree with some pre selected options and then there is a button like reset, on clicking that i want to refresh my page without any pre selected options....can u please provide any option like refresh?

do not selected default

<select>
<option selected></option>
<option selected></option>
<option selected></option>
</select>

The tree not checked those items which has selected attribute

No Scroll ?

I have added scroll bar when the list is big. please update it your application.

div.tree-multiselect {
max-height: 218px;
overflow-y: scroll;
display: inline-block;
}

Limit the height of the selected options

Good Morning,

I am trying to limit the height of the column of selected elements, in order to make it scrollable, I have come to use in the inspector even the element.style selector, forcing the height even with important.

I have not been able to make that listing fit the desired height.

Could you help me?

Thx so much!
Luisfermp

How to check the parent node is selected?

If I have tree like this,

  • Parent 1 (value:parent1)
    • Child 1 (value:child1)
    • Child 2(value:child2)
    • Child 3 (value:child3)
  • Parent 2
    • Child 4
    • Child 5
    • Child 6

As per your code, when I click Parent 1, whole child 1, child 2 and child 3 will be selected. Thats good. But. How can I check whether is selected parent node or child nodes? Suppose I click Child2, value selected is displaying as child2, and if Parent 1 is selected, values selected are displaying as child1, child2 and child3. instead of displaying all 3, is there any possiblity display only value = parent1 when click Parent1 ?

data-section plus prefix doesn't change to minus when opened from a search

The plus prefix of a data-section only changes when clicked directly. When you type something search, all the relevant data-sections open themselfes but without changeing the prefix to a minus. When you click the data-section after a search, it does change, but the wrong way around.

The tree is initialized with the parameter startCollapsed: true

just one option with no child

Hi @patosai, how to do if I want to have only one option with no child?
example

1.Menu A
- Sub Menu A.1
- Sub Menu A.2
2. Menu B
3. Menu C
4. Menu D
- Sub Menu D.2

Request: Single Select

I love this control. Recently I came upon a situation where I needed to have cascading dropdowns so a user can navigate a hierarchy down to a single record. I thought perhaps instead of these cascading dropdowns which is hard to navigate I would use your multi-select tree. It works perfect for my needs including searching, the only problem is I want to limit the user to a single selection.

So I'm requesting the ability to include a config property that lets me specify a limit to the number of selected items. That way I could specify 1 for a single select, or 3 for a multi-select with a limit of 3 selected and no more.

Form returning only one item and not multiple selection

I am using the below markup to use your excellent library. It works fine.

But when I select multiple values and submit the form, I get only 1 selected items.

Fore example, if I select "Category 1" and "Category 2-a" and submit the form, the forum values has only "Category 2-a" and not other value.

<select name="itemCategory" id="category" multiple="multiple">
   <option value="1" data-section="Main Categories">Category 1</option>
   <option value="2" data-section="Main Categories">Category 2</option>
   <option value="3" data-section="Main Categories">Category 3</option>
   <option value="4" data-section="Category 2">Category 2-a</option>
</select>

Checkbox text should be in label tag

Just implemented tree-multiselect.js. It's a really nifty plugin, however, it would greatly help usability if the text for each checkbox was wrapped in an associated label tag. Then you could click the label text or the checkbox to select the checkbox, instead of just the small textbox target area.

For example, in a section titled "Brooklyn"

<div class="item" data-value="Flatbush" style="display: block;">
    <input type="checkbox">Flatbush
</div>

With some sort of name-spaced generated ID becomes:

<div class="item" data-value="Flatbush" style="display: block;">
    <input type="checkbox" id="tms-brooklyn-flatbush"><label for="tms-brooklyn-flatbush
</div>

What do you think?

Issue in IE while removing nodes and batch select.

Hi, I got an error in IE while it tries to remove the nodes.

Fixed it by replacing node.remove(); by $(node).remove();

Also, (and just as a suggestion), the event that can be captured for selectionContainer can be 'click'. In this way, IE will trigger the event even when the checkbox properties indeterminate is true and checked is false.

Great work! and hope this helps to you

Cheers!

Leo

On demand load for large dataset

Hi,
I think this is is more of a enhancement than anything . As-is the component works perfectly.
But in one of the business-cases the rendering is quiet slow when the size of data is large.
On my end, the data has 8 levels with around 8000 nodes so loading the data at the begging is a quiet slow.

So, I was thinking of loading first few levels or 1st level of data to start with and then loading the other data using async requests. But looking at the design of the component i'm a bit lost as to how can I achieve that.

Has anyone given a thought to this or have any ideas ? I know this will affect the search and other features drastically, but will give a really nice alternative to showing large data.

PS.. Please feel free to move this post to either enhancement or something.. i'm new to GitHub so don't really know how the tagging thing works.

how to select item with js?

I want implement radio function, when user click optgroup2's item, optgroup1's items will unchecked.
how can i do this??

is it possible that section should be act like node ?

I know this is not issue its extra functionality.
Consider Following Tree :

  • Section A
    • Node A
    • Node B
    • Node C

If i have selected section A i want to use section A as node and want to add it into right side Stack? Could you (@patosai) please help me on this?

Help to use this plugin

I need to do the same example in the link can u help me..

I included

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script type="text/javascript" src="jquery.tree-multiselect.min.js"></script>
</script>
<script type="text/javascript"> function treeOnChange(allSelectedItems, addedItems, removedItems) { console.log(allSelectedItems); } $("select").treeMultiselect({ onChange: treeOnChange, searchable: true, searchParams: ['section', 'text'] }); </script>

Feature request: option to mark the tree as read-only

Hi. Thanks for this component. It works great and it's very usable.

I've come to an scenario that requires the entire tree to be frozen for updates (a tipical crud). So far, I've come to solve the requirement by enclosing the component within a disabled fieldset and then unbinding the events on the span, something like this:

HTML:

<fieldset id="read-only-tree" disabled="disabled">
   <select id="tree" multiselect="multiselect">...</select>
</fieldset>

Javascript:

$(document).ready(function () {
                var options = {
                    allowBatchSelection: false
                };
                $("#tree").treeMultiselect(options);
                $("#read-only-tree span.remove-selected").unbind();
});

However, I find this kind of hackish, so having this functionality would be awesome.

Thanks again.

Enhancement suggestion - disabled prop

Locally, I've extended your library to handle option[disabled=true], rendering a disabled, unselectable input checkbox. Haven't gotten around to propagating that up to parent checkboxes, but nonetheless a useful feature imo.

Set value to parent node

Hey, I'm using this widget and it's really good. But now I'm wondering, how can I set the value for a parent node? I mean, I have this:

<option data-section="All/Image" value="someValue">HD</option>
<option data-section="All/Image" value="someValue">Series</option>
<option data-section="All/Image/Books" value="someValue">Dutch</option>
<option data-section="All/Image/Books" value="someValue">English</option>

So, its displayed as:
|---All
|-------Image
|-------------HD
|-------------Series
|-------------Books
|-------------------Dutch
|-------------------English

And it's going well until here, but now, How I set a value only for the Image option? when the users select Image I want to send a value for it

no bower ?

How can i get tree-multiselect throught bower.

I just got src document.

Thanks

Construct nested structure based on parent

Hi,
Congrats for your project, it is really helpful.

However I have a question. Would it be possible to construct nested structure, only by giving the parent's node value and not the full path? It would be really helpful in situations where is hard to get the full path.

Thank you in advance.

Duplicated entries

When I try to add dynamically new options and reinitialize the treeview the options appear twice

Predefined selection do not repopulate after select element is recreated programaticaly

Here is the scenario:
A select element is created in JS code like this:

someSelect = $('<select id="someSelect" multiple="multiple"></select>');
for(var key in data.result.somedata){
     group = data.result.somedata[key];
     $.each(group, function() {
          someSelect.append('<option value="' + this +
                 '" data-section="' + key + '">' + this + '</option>');
     });
 }

then later in the code pre-selected options (based on their presence in cols array) are marked and tree-multiselect is created:

$("div#graphDataBox").append(someSelect);
$("select#someSelect option").removeAttr("selected");
$("div.tree-multiselect").remove();
$.each($("select#someSelect option"), function() {
    if(cols.indexOf($(this).val()) > -1) {
        $(this).attr("selected", "selected");
    }
});

$("select#strategies").treeMultiselect({startCollapsed: true});

Everything works like a charm at the first page load.
Once the code retrieves the new set of cols via an Ajax request from the back-end repopulation of the tree-multiselect pre-selections fails. I checked the someSelect options are correwctly mark as selected (done in $.each function) when the data come back from the Ajax call.

What do I miss when cleaning up before rebuilding?

Thank you

Martin

Can select a section without selecting all the childs?

Can select a section without selecting all the child's?

i have this hierarchy:

Drinks
->Whisky
->Irish
->Scotch
->Soda
->Coca Cola

I need to select section "Whisky" without selecting irish and scotch.
Is any option or attribute i can use for this?

Order of tree nodes

Hi i would like to ask if there is possibility to set order of tree nodes... problem is that if i have 3 child nodes and only one has another children this node is pushed to end. Example for better imagination:

This is how i want to sort tree items

  • a
    • a1
    • a2
  • b
  • c

But i always get

  • b
  • c
  • a
    • a1
    • a2

so tree item with children goes always to the end of tree... if all tree items has children, order is ok - this happens only if not all same-level-items has other children

is there some workaround or config or?

Thanks

Have it not apply to a certain select list

Hey there,

Great component - I had a simple question.. the component works great on the list that I want converted into a multi-select tree. I have another select list that I do not want converted into a multi-select tree.. so how do I make it so that shows as a normal select drop-down list?

thanks in advance

Collapse after clearing search box

Great plugin. Thanks. When I type something into the search box, the nodes that contain matching items are expanded and displayed. Then I can select one of the items. But then when I clear the search box, I'm left with all the nodes in the whole tree expanded. I have lots of nodes so that makes it pretty difficult to browse the tree. It would be better if, after clearing the search box, all nodes collapsed again like they are when the page loads. Or, another option might be to have a button to collapse all. Thanks.

Reload Options @ ajax response

All those things worked well at page loading,
but I want to append options from ajax response.
But 'tree-multiselect' div is not reloading/refreshing.
Could you help me to solve this problem or add an example to your site...?

Thanking you,
SAIF

Adding "Select All" and "De Select All"

It would be really helpful to have methods to be able to select all and select none. I tried to achieve this (see below hacky code), but the information doesn't seem to be saved:

$("#btnSelectAll").on('click',function() {
event.preventDefault();
$("#PromptPanel1_treeviewCommentCodes > option").each(function(){
$(this).attr('selected','selected');
});
$(".tree-multiselect input").each(function(){
$(this).attr('checked','checked');
});
});

            $("#btnDeSelectAll").on('click',function() {
                event.preventDefault();
                $("#PromptPanel1_treeviewCommentCodes > option").removeAttr("selected");
                $(".tree-multiselect input:checked").removeAttr("checked");
            });

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.