Add custom attribute to option in select2 - javascript

I am using select2 plugin, in that I want to add custom attribute to options
"data-value".
$('select').select2({
data: [
{
id: 'value',
text: 'Text to display'
},
]
});
If I add "data-value" in above code it will not display that option.
Is there any way to do such thing.
I am using 4.* select2 plugin

I use Select2 4.0.5 with the help of Event 'select2:select' to achieve this.
At initialization there is no effect, when you select one option, the attribute will add to it.
$(element).select2(
{
placeholder:'chose one option',
data:[ {
"id": 1,
"text": "Option 1",
"data-value":"dv1",
},
{
"id": 2,
"text": "Option 2",
"data-value":"dv2",
}]
}).on('select2:select', function (e) {
var data = e.params.data;
$(this).children('[value="'+data['id']+'"]').attr(
{
'data-value':data["data-value"], //dynamic value from data array
'key':'val', // fixed value
}
);
}).val(0).trigger('change');
the .val(0).trigger('change') used for show placeholder and let it no default. otherwise the first option will be default with no attribute add on.
Init :
when select "Option 2" :

select2 use like this way :
for(var i = 0; i < arr.length; i++)
{
$('select').append('<option data-value="'+arr[i].DataValue+'" value="'+arr[i].Id+'">'+arr[i].Text+'</option>');
}
$('select').select2();
after appending the options you need to call select2() function

Related

Adding dynamic values to select for every row in Tabulator

I have a list of items. Each item contains a list within it as well. I want to add that list in dropdown in tabulator. I am using tabulator v4.4.1.
Item 1:
{
"attribute1": "Value1",
"attribute2": "Value2",
"list": [ "ListItem1", "ListItem2" ]
}
Item 2:
{
"attribute1": "Value1",
"attribute2": "Value2",
"list": [ "ListItem1", "ListItem2", "ListItem3" ]
}
Each item has different list. I want to add ListItems in a dropdown in a cell in tabulator.
{
title: "List",
field: "list",
editor: "select",
editorParams: function(cell) {
var values = {};
var list = cell.getData().list;
list.forEach(function(item) {
values[item] = item;
});
return {
values: values
};
}
}
However this code does not attach values to dropdown. Where am I going wrong?
If it is a simple array then you can significantly simplify your example as that can be passed directly into the values property.
{
title: "List",
field: "list",
editor: "select",
editorParams: function(cell) {
return {
values: cell.getData().list
};
}
}
Im assuming that there is an error in your example and that the list column should be separate from the column with the editor on. otherwise there would be no list to show because the value of the column would replace it

How to set placeholder to a table filter?

I'm trying to add a placeholder in the Webix table filter like next:
columns:[
{
id:"title", header:["Film title", {
content:"richSelectFilter", // placeholder:"Select the movie..." doesn't work
}], width:300
},
{ id:"rating", header:"Rating", width:100 }
]
Sample: http://webix.com/snippet/cac752a6
This works for the usual richSelect widget, but I can't find a way to change config for the same table filter. Is it possible? Thanks.
You can use a code like next to set placeholder for the rich-select filter
columns:[
{
id:"title", header:["Film title", {
content:"richSelectFilter", inputConfig:{ placeholder: "text here" }
}], width:300
},
http://webix.com/snippet/58b054a2
or, if you want to change the placeholder dynamically
var select = $$("d1").getFilter("title");
select.define("placeholder", "Some text here");
select.refresh();
http://webix.com/snippet/bd31c1f6

Kendo, kendoDropDownList, _selectedValue, always the first option

This is probably easy but I'm stuck.
I have a function that works with a kendoDropDownList and I cannot retrieve the value of the selectedIndex. Ignoring what the function actually does, can someone explain this?
function setDocTypeAssociates(event){
var dropdownlist = $("#type_doma_ky").data("kendoDropDownList");
console.log(dropdownlist);
console.log(dropdownlist._selectedValue);
console.log(dropdownlist.selectedIndex);
...
The result of those three console.log()s you can see in the attached screendump.
Why are the values correct (65 and 4) in the object, yet incorrect (67 and 0) when I dump them individually?
It is really hard to say why you get these results, I personally tried to reproduce them and was unable.
Any way the best way to get your data would be:
var dropdownlist = $("#list").data("kendoDropDownList");
console.log(dropdownlist);
console.log(dropdownlist.text());
console.log(dropdownlist.value());
console.log(dropdownlist.selectedIndex);
with text() and value() functions.
In general Telerik does not recommend using fields that start with underscore because they are setup for internal use and might change. For example in the latest version of Kendo UI _selectedValue returns undefined.
I have created working example for your reference.
http://dojo.telerik.com/eNUkU
look at this fiddle:
(https://jsfiddle.net/cr1v6cvh/1/)
Get Data
<script>
$("#btnGetData").kendoButton({
click: function (event){
var dropdownlist = $("#dataList").data("kendoDropDownList");
console.log(dropdownlist);
console.log(dropdownlist.text());
console.log(dropdownlist.value());
console.log(dropdownlist.selectedIndex);
}
})
$(document).ready(function() {
$(".ddlData").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "data 1", value: "1" },
{ text: "data 2", value: "2" },
{ text: "data 3", value: "3" },
{ text: "data 4", value: "4" }
]
});
});
</script>

How to create Tree with checkboxes using JSON data with Parent Child Relation?

I have JSON data and that JSON data has parent child relation . I Want to create tree structure from it. i found many plugins and libraries but i can't found my requirement . I am getting this JSON data using PHP script.
Here is image that has tree structure that i want to create . i'm stuck at it.I know JSON is not as displayed in image but i only want to show you what a tree should look like .How to create tree like in image.All i want is javascript code to handle and create this type of structure of tree . Working example is must & much appreciated.
You can use JSON format as you like and tree should be collapsible.Also provide required JSON format for it.
and my JSON data as follows :
{
"2":
{
"5": "Wrist Watch"
},
"5":
{
"9": "Men's"
},
"18":
{
"3": "Clothing"
},
"28":
{
"1": "Perfumes"
},
"29":
{
"7": "Laptop",
"10": "Tablets"
},
"30":
{
"8": "Mobile"
},
"31":
{
"2": "Books"
},
"33":
{
"6": "Electronics"
},
"34":
{
"4": "Home & Kitchen\n"
}
}
If you want to roll your own, the keyword in "trees" is recursion. It needs to support any depth of data and the code and data should both support recursion.
This means your JSON data should be a recursive structure, where each node looks the same (and looks something like this):
{
id: 1, // data id
title: "title", // display title
children: [ // list of children, each with this same structure
// list of child nodes
]
}
Note: I have changed the sample data to contain more depth as 2 levels never shows up recursion problems.
e.g.:
{
id: 0,
title: "root - not displayed",
children: [{
id: 1,
title: "Option 1",
children: [{
id: 11,
title: "Option 11",
children: [{
id: 111,
title: "Option 111"
}, {
id: 112,
title: "Option 112"
}]
}, {
id: 12,
title: "Option 12"
}]
}, {
id: 2,
title: "Option 2",
children: [{
id: 21,
title: "Option 21"
}, {
id: 22,
title: "Option 22"
}]
}, {
id: 3,
title: "Option 3",
children: [{
id: 31,
title: "Option 31"
}, {
id: 32,
title: "Option 32"
}]
}]
}
The recursive function looks like this:
function addItem(parentUL, branch) {
for (var key in branch.children) {
var item = branch.children[key];
$item = $('<li>', {
id: "item" + item.id
});
$item.append($('<input>', {
type: "checkbox",
name: "item" + item.id
}));
$item.append($('<label>', {
for: "item" + item.id,
text: item.title
}));
parentUL.append($item);
if (item.children) {
var $ul = $('<ul>').appendTo($item);
addItem($ul, item);
}
}
}
JSFiddle: http://jsfiddle.net/0s0p3716/188/
The code recurses the structure, adding new ULs and LIs (with checkbox etc ) as it goes. The top level call just provides the initial root starting points of both the display and the data.
addItem($('#root'), data);
The end result looks like this:
If you want to toggle visibility, based on the checked state, use this:
$(':checkbox').change(function () {
$(this).closest('li').children('ul').slideToggle();
});
If you also want the labels to toggle the checkboxes, use this:
$('label').click(function(){
$(this).closest('li').find(':checkbox').trigger('click');
});
Note: I have only provided the most basic of styling as that will typically be "to taste". Examples in links were shown in another answer.
-- updated:
amended: possible wrong ids for items 31 & 32?
function for better selection and deselection(for parents cascading into child nodes):
$(function () {
addItem($('#root'), data);
$(':checkbox').click(function () {
$(this).find(':checkbox').trigger('click');
var matchingId = $(this).attr('id');
if ($(this).attr('checked'))
{
$('input[id*=' + matchingId +']').each(function() {
$(this).removeAttr('checked');
$(this).prop('checked', $(this).attr('checked'));
});
}
else {
$('input[id*=' + matchingId +']').each(function() {
$(this).attr('checked', 'checked');
$(this).prop('checked', $(this).attr('checked'));
});
}
});
$('label').click(function(){
$(this).closest('li').children('ul').slideToggle();
});
-- Update the fiddle with this as shown here(JsFiddle) and it will work better and also will allow you to click the text to expand without selecting at the same time - I know I find this far more useful. It will help (and this is personal preference) you to see what values and options are available without having to select the first.
The thing with programming is: existing libraries and tools rarely do exactly what you need. It's always up to you to convert the input data into exactly the format they expect and then the output data into the format you need. Occasionally this conversion requires more effort than writing your own code instead of a library function - this seems to be one of those occasions.
As #philosophocat already noted, the best way to present such a tree in HTML markup would be nested lists. All you need is iterate through the JSON data recursively and create the corresponding elements:
function createList(data)
{
var result = document.createElement("ul");
for (var key in data)
{
if (!data.hasOwnProperty(key) || key == "_title")
continue;
var value = data[key];
var item = createItem(key, typeof value == "string" ? value : value._title);
if (typeof value == "object")
item.appendChild(createList(value));
result.appendChild(item);
}
return result;
}
function createItem(value, title)
{
var result = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("name", "selection");
checkbox.setAttribute("value", value);
result.appendChild(checkbox);
result.appendChild(document.createTextNode(title));
return result;
}
document.body.appendChild(createList(jsonData));
Note that the order in which the items appear is "random" here, as object keys are generally unordered. You can change the code above to sort the keys somehow, or you can change the data to use arrays and define an order. I also added a "_title" property to the data to make sure the categories are labeled - your data doesn't have any labels at all for the categories.
Now you need to style the lists in such a way that they look like a tree. The obvious solution is using the list-style-image CSS property to replace the usual bullet points by a grid lines image. However, that doesn't work for nested lists - there you need to show multiple images, vertical lines from the higher-level lists as well as the image actually belonging to the current list item.
This can be solved by using background images for the list items instead, these background images will be shown next to sublists as well then. Here are the example styles I've got:
ul
{
padding: 0;
list-style-type: none;
font-size: 14px;
}
li
{
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAABkCAYAAABdELruAAAAP0lEQVR42u3PQQoAIAgEQP3/o6t7JAhdolkQD4sMZuwZazKKlGXniHRDOu6HfyKRSCQSiUQikUgkEolEIv0rTc/fNmQ78+lPAAAAAElFTkSuQmCC);
background-repeat: no-repeat;
padding-left: 13px;
}
li:last-child
{
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAHUlEQVR42mNkwAT/gZiRAQ/AK0mKplGbqGETThoACFgJCVdBEqAAAAAASUVORK5CYII=);
}
li > ul
{
margin-left: 5px;
}
Note that this will still get ugly if the sublist is too high - the height of the background image I used is merely 100px. This can be solved by using a larger background image of course. A cleaner alternative would be using border-image-slice CSS property but that one is currently only supported in Firefox.
Fiddle for this code
Edit: This article goes into more detail on styling nested lists like a tree. While the approach is similar, it manages to avoid the image size issues I mentioned above by using a separate image for the vertical line which can be repeated vertically. On the downside, that approach looks like it might only work with solid lines and produce artifacts if applied to dotted lines.
Use http://www.jstree.com/. This library provides each function I ever need when working with trees and javascript.
You simple have to change your json-response according to the given format (http://www.jstree.com/docs/json/):
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
Set up the javascript and include all required files and there you go.
I just skip repeating the documentation by referring to it: http://www.jstree.com/
I'm using DynaTree for an internal site at work and it works fantastic.
Download DynaTree
Format your JSON as such (taking your screenshot as an example):
{
"title": "Sports & Outdoors",
"isFolder": true,
"key": "0",
"children": [
{
"title": "Fitness Accessories",
"key": "1",
"isFolder": true,
"children": [
{
"title": "Fitness Accessories",
"key": "2",
"isFolder": true,
"children": [
{
"title": "Pedometer & Watches",
"key": "3"
}
]
}
]
}
]
}
Run this JS on page load:
$("#buildTree").dynatree({
onActivate: function (node) {
// A DynaTreeNode object is passed to the activation handler
// Note: we also get this event, if persistence is on, and the page is reloaded.
leftActiveNodeKey = node.data.key;
},
persist: false,
checkbox: true,
selectMode: 3,
children: $.parseJSON(response.d)
});
To get the selected nodes you can use:
var selectedNodes = $("#buildTree").dynatree("getTree").getSelectedNodes();
Dynatree is pretty customization, both in look and function. Read through the documentation for the settings you need.
Check these sites.Hope this helps.
http://www.jstree.com/docs/json/
http://www.jeasyui.com/documentation/tree.php
http://jqwidgets.com/jquery-widgets-demo/demos/jqxtree/index.htm#demos/jqxtree/checkboxes.htm
#Gone Coding's example is excellent, but the child check boxes will not show as 'uncheked' even though the checked attribute is removed, as rendered in Chrome.
If you add,
$(this).prop('checked', false);
to the code, so it reads as
$(function () {
addItem($('#root'), data);
$(':checkbox').click(function () {
var matchingId = $(this).attr('id');
if ($(this).attr('checked'))
{
$('input[id*=' + matchingId +']').each(function() {
$(this).removeAttr('checked');
$(this).prop('checked', false);
$(this).prop('checked', $(this).attr('checked'));
return;
});
}
else {
$('input[id*=' + matchingId +']').each(function() {
$(this).attr('checked', 'checked');
$(this).prop('checked', $(this).attr('checked'));
});
}
});
$('label').click(function(){
$(this).closest('li').children('ul').slideToggle();
});
});
the child check boxes will fill or clear when the user makes a change.

Fill dropdown list with json

I have SQLite table with columns id and name. I return array of those rows like json from autocomplete.php page. How to fill select with options ( drop down list ) with this json using jquery and JavaScript ? I am new to JavaScript and JQuery, I googled but didn't find how. In ASP.NET this is easy but here I don't know. Would somebody help ?
This is example of my JSON, can be much longer.
[
{
"id": "1",
"name": "test"
},
{
"id": "1",
"name": "test"
}
]
HTML:
<select id="sel">
</select>
JavaScript:
$(function() {
var data = [
{
"id": "1",
"name": "test1"},
{
"id": "2",
"name": "test2"}
];
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});
})
Here's a working example. http://jsfiddle.net/ms2Ma/
Try this, This will give you an option to have any number of dropdown boxes and JSON nodes to configure dropdown boxes.
You need to follow few steps:
Create an array of dropdown boxes.(e.g. if you have to configure a phone then you should be using dropdown of color, memory etc.)
Create a JSON object as it is created in code. Dont change the configurable items name which starts with "level1" and end with any number of nodes, As it has to be sync with the index of items of array you are creating in the first place.
Here is the data:
var Dropdowns = ["Model", "Color", "Memory","design","covers","music"];
var Data ={"phones":[
{
"oid":":000000F0:00000458:",
"level1":"3G",
"level2":"white",
"level3":"16GB",
"level4":"slim",
"level5":"Back cover",
"level6":"headphone",
"price":"£568.63",
"addToCart":"#Cart1"
},
{
"oid":":000000F0:000003DA:",
"level1":"3G",
"level2":"black",
"level3":"16GB",
"level4":"slim",
"level5":"Flip cover",
"level6":"headphone",
"price":"£615.79",
"addToCart":"#Cart7"
}]};
See the full working code here:
https://jsfiddle.net/raju_sumit/681ppgq0/5/
Try this :)
Javascript:
$.getJSON("/array.json",
function (json) {
$.each(json,
function (key, value) {
$("#id-select").append("<option value='" + value.c + "'>" + value.d + "</option>");
});
});
A pure Javascript solution: this snippet shows how to populate a dropdown select from JSON data (using id as value and name as text.
The code creates a new Option object for each item in the JSON data and appends it to the select element with appendChild(). map is used in place of a for loop.
let data = [{
"id": "1",
"name": "name_1"
},
{
"id": "2",
"name": "name_2"
}
];
var selectElement = document.getElementById('mySelect');
data.map(item => mySelect.appendChild(new Option(item.name, item.id)).cloneNode(true));
<select id="mySelect" onchange="alert(this.value)"></select>

Categories

Resources