Adding dynamic values to select for every row in Tabulator - javascript

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

Related

Add custom attribute to option in select2

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

How to get a specific or multiple values (or keys) from nested JSON

I have a (nested) data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
{
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
jQuery
var pk = $("#pk").val();
console.log(pk);
url = "/register/search?id=" + pk;
console.log(url);
$('#largeTable').DataTable({
"ajax": url,
"bDestroy": true,
"columns": [{
"data": "name"
},
{
"data": "value"
},
{
"data": "list.1.sname"
},
{
"data": "list.1.svalue"
},
{
"data": null,
"defaultContent": editview
}
]
});
Here it is possible to display either first or second list values by using list.1 or list.0
But I want two values at a time.
Also, how could I access the svalue of the second item in list?
I tried with data.list[1] but:
TypeError: data.list is undefined
Since data is an array, you should first get the item - and since you only have one item - you'd use data[0], and then get access to the list property like data[0].list[1] - this will give you the second item in the list - but since you are interested in a specific property (svalue) of this item, you will then access it like this: data[0].list[1].svalue.
A better approach would be to loop through the items in the data array - and then for each item, loop through the items in the list array. See #Rajesh's comment.
I hope that helps;
Specifically you can access it like this object.data[0].list[1].svalue. The reason data.list is undefined is because data corresponds to an array data: [{ }] this is why we use data[0], but data itself is a key in an object so before you can get to data you need to access it. If the objects name where data resides were object (like I did below) then it'd be accessed like this object.data[0]
const object = {
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
console.log(object.data[0].list[1].svalue)

how to add data in a row or kendo Grid

I have a scenario where I want to fill some of the kendo grid columns by program. So I assume that I have to catch the row and fill data in the columns.
I am able to fetch the row ID based on some event(click for example). But I have no Idea how to update the value of a column bases on row id pragmatically.
http://jsfiddle.net/xojke83s/4/
above is the JS fiddle where I am able to get the row ID of a particular row. I want to know the way fill some data in any of the column by program. In the above example that column should be operationContext.
following is the code for same -
<div id="grid"></div>
$("#grid").kendoGrid({
"dataSource": {
"schema": {
"model": {
"id": "id",
"fields": {
"OperationContext": {
"type": "string",
"editable": "false"
}
}
}
}
},
"editable": "popup",
"toolbar": [
{
"name": "create",
"text": "Add a New Record"
}
],
"columns": [
{
"field": "Name",
"title": "Name"
},
{
"field": "Age",
"title": "Age"
},
{
"field": "OperationContext",
"title": "Operation Context"
},
{ command: ["edit", "destroy"], title: " ", width: "250px" }
]
});
$(".k-grid-add").on("click", function () {
var grid = $("#grid").data("kendoGrid").dataSource.data([{OperationContext: "IsAdded"}]);
});
//bind click event to the checkbox
var grid = $("#grid").data("kendoGrid"); 
grid.bind("edit", grid_edit);
function grid_edit(e){
console.log(e.model.uid);
}
Thanks in advance.
Answer made from comment as requested
I have updated your fiddle with this: updated js fiddle
I have modified the edit code to do this:
function grid_edit(e){
console.log(e.model);
if(!e.model.isNew() || e.model.id === 0){
e.model.set("OperationContext","I am being updated");
}
}
It will only add the inserting (defaultValue) and updating text in for new items or where an id is greater than 0.
I can see the logic for newly created items and maybe for edited items if the value is blank or if it is being used as a status tracker.
But if you delete an item then surely that is deleted from your datasource and you will no longer have access to that item so why store an update/indicate an update to a value when it is to be deleted.

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