Our club needs to type members in an input field and have the parent li background color change based on the name lookup in a supporting json file. I would prefer a jquery solution, but javascript is OK!
All is included in the link https://jsfiddle.net/24n2on57/7/
HTML:
<ul id="sortable">
<li id="L01"><input type="text" id="I01"></li>
<li id="L02"><input type="text" id="I02"></li>
<li id="L03"><input type="text" id="I03"></li>
<li id="L04"><input type="text" id="I04"></li>
</ul>
JS:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
var standing = [{
"code": "A",
"background": "#AEF3D4"
},
{
"code": "B",
"background": "#6DDCEA"
},
{
"code": "C",
"background": "#9CC7CC"
},
{
"code": "D",
"background": "#B37F77"
}
];
</script>
<script>
var members = [{
"Class": "A",
"Name": "Bob"
},
{
"Class": "C",
"Name": "James"
},
{
"Class": "D",
"Name": "Thomas"
},
{
"Class": "B",
"Name": "Anthony"
}
]
</script>
<script>
// Lookup background color
function getBackground(name) {
var i = null;
for (i = 0; members.length > i; i++) {
if (members[i].Name === name) {
return standing[i].background;
$(this).css('background-color', standing[i].background);
}
}
return;
};
$("#I01").on("blur", function() {
$("#L01").val(getBackground($(this).val()));
})
$("#I02").on("blur", function() {
$("#L02").val(getBackground($(this).val()));
})
$("#I03").on("blur", function() {
$("#L03").val(getBackground($(this).val()));
})
$("#I04").on("blur", function() {
$("#L04").val(getBackground($(this).val()));
})
</script>
You have to set css instead of val. Also, you had multiple unnecessary style tags in your jsfiddle. I removed them and added the working code here.
For the first list element I added styling using javascript and for the others I used jQuery in-order to show you how to do it in both ways.
var standing = [{
"code": "A",
"background": "#AEF3D4"
},
{
"code": "B",
"background": "#6DDCEA"
},
{
"code": "C",
"background": "#9CC7CC"
},
{
"code": "D",
"background": "#B37F77"
}
];
var members = [{
"Class": "A",
"Name": "Bob"
},
{
"Class": "C",
"Name": "James"
},
{
"Class": "D",
"Name": "Thomas"
},
{
"Class": "B",
"Name": "Anthony"
}
]
$(this).css('background-color', 'red');
function getBackground(name) {
var i = null;
for (i = 0; members.length > i; i++) {
if (members[i].Name === name) {
return standing[i].background;
//$(this).css('background-color', standing[i].background); // Don't put any code after 'return' statement
}
}
return;
}
$("#I01").on("blur", function() {
document.getElementById("L01").style.backgroundColor = getBackground($(this).val());
});
$("#I02").on("blur", function() {
$("#L02").css({"background-color":getBackground($(this).val())});
});
$("#I03").on("blur", function() {
$("#L03").css({"background-color":getBackground($(this).val())});
});
$("#I04").on("blur", function() {
$("#L04").css({"background-color":getBackground($(this).val())});
});
#myDiv,
#intro {
display: table;
width: 30rem;
margin: 2rem auto
}
li {
background: lightgreen;
margin: 1rem;
height: 3rem;
line-height: 3rem;
list-style-type: none;
}
input {
background: #fff;
height: 2rem;
line-height: 2rem;
font-size: 1.5rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="grid-container" style="margin-top:4rem">
<div id="intro">
The color of the list items (default background = "lightgreen") is to be based on the lookup members.Name and return of the standing.background. Valid names are "Bob", "James", "Thomas", and "Anthony". User types in a name, presses tab (onblur) and the
list item background changes to standing.background.
</div>
<div id="myDiv" class="grid-item">
<ul id="sortable">
<li id="L01"><input type="text" id="I01"></li>
<li id="L02"><input type="text" id="I02"></li>
<li id="L03"><input type="text" id="I03"></li>
<li id="L04"><input type="text" id="I04"></li>
</ul> </div>
</div>
Here is the solution for your problem.
var standing = [{
"code": "A",
"background": "#AEF3D4"
},
{
"code": "B",
"background": "#6DDCEA"
},
{
"code": "C",
"background": "#9CC7CC"
},
{
"code": "D",
"background": "#B37F77"
}
];
var members = [{
"Class": "A",
"Name": "Bob"
},
{
"Class": "C",
"Name": "James"
},
{
"Class": "D",
"Name": "Thomas"
},
{
"Class": "B",
"Name": "Anthony"
}
]
$(this).css('background-color', 'red');
function getBackground(name) {
var i = null;
for (i = 0; members.length > i; i++) {
if (members[i].Name === name) {
return standing[i].background;
$(this).css('background-color', standing[i].background);
}
}
return;
};
$('input').on('input', function() {
var input = $(this).val();
$(this).parent().css('background-color', searchMembers(input));
});
function searchMembers(name){
var className = '';
for (var i=0; i < members.length; i++) {
if (members[i].Name === name) {
return searchStanding(members[i].Class);
}
}
}
function searchStanding(className){
for (var i=0; i < standing.length; i++) {
if (standing[i].code === className) {
return standing[i].background;
}
}
}
#myDiv,
#intro {
display: table;
width: 30rem;
margin: 2rem auto
}
li {
background: lightgreen;
margin: 1rem;
height: 3rem;
line-height: 3rem;
list-style-type: none;
}
input {
background: #fff;
height: 2rem;
line-height: 2rem;
font-size: 1.5rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change BG color of list item based on json lookup</title>
</head>
<body>
<div class="container">
<div class="grid-container" style="margin-top:4rem">
<div id="intro">
The color of the list items (default background = "lightgreen") is to be based on the lookup members.Name and return of the standing.background. Valid names are "Bob", "James", "Thomas", and "Anthony". User types in a name, presses tab (onblur) and the
list item background changes to standing.background.
</div>
<div id="myDiv" class="grid-item">
<ul id="sortable">
<li id="L01"><input type="text" id="I01"></li>
<li id="L02"><input type="text" id="I02"></li>
<li id="L03"><input type="text" id="I03"></li>
<li id="L04"><input type="text" id="I04"></li>
</ul </div>
</div>
</body>
</html>
I just changed the JQuery part. All You need is changing the li back ground color depending on name.
var standing = [{
"code": "A",
"background": "#AEF3D4"
},
{
"code": "B",
"background": "#6DDCEA"
},
{
"code": "C",
"background": "#9CC7CC"
},
{
"code": "D",
"background": "#B37F77"
}
];
var members = [{
"Class": "A",
"Name": "Bob"
},
{
"Class": "C",
"Name": "James"
},
{
"Class": "D",
"Name": "Thomas"
},
{
"Class": "B",
"Name": "Anthony"
}
]
function getBackground(name,selector) {
var i = null;
for (i = 0; members.length > i; i++) {
if (members[i].Name == name) {
for (k = 0; standing.length > k; k++) {
if (members[i].Class == standing[k].code) {
$(selector).parent().css('background-color', standing[k].background);
}
}
}
}
return;
};
$("#I01").on("blur", function() {
getBackground($(this).val(),this);
})
$("#I02").on("blur", function() {
getBackground($(this).val(),this);
})
$("#I03").on("blur", function() {
getBackground($(this).val(),this);
})
$("#I04").on("blur", function() {
getBackground($(this).val(),this);
})
Also check the fiddle https://jsfiddle.net/24n2on57/39/
Related
I have nested checkboxes with a tree hierarchy level. It contains also both indeterminate and checked status for each level. Basically, I need to store each checked / indeterminate value of the checkbox in an array with the correct level. Unfortunately, I'm not able to include indeterminate values with the current solution. Is there any way we can search for two elements (input:checked,input:indeterminate) at the same time?
function toggleCheckboxArea(onlyHide = false) {
var checkboxes = document.getElementById("SelectOptions");
var displayValue = checkboxes.style.display;
if (displayValue != "block") {
if (onlyHide == false) {
checkboxes.style.display = "block";
}
} else {
checkboxes.style.display = "none";
}
}
let data = {
"Tall Things": {
"label": "Tall Things",
"children": {
"Buildings": {
"label": "Buildings",
},
"Two sandwiches": {
"label": "Two sandwiches",
},
"Giants": {
"label": "Giants",
"children": {
"Andre": {
"label": "Andre",
},
"Paul Bunyan": {
"label": "Paul Bunyan",
}
}
}
}
},
"Tall' Things 2": {
"label": "Tall' Things 2",
"children": {
"Buildings 2": {
"label": "Buildings 2",
},
"Two sandwiches 2": {
"label": "Two sandwiches 2",
},
"Giants 2": {
"label": "Giants 2",
"children": {
"Andre 2": {
"label": "Andre 2",
},
"Paul Bunyan 2": {
"label": "Paul Bunyan 2",
}
}
}
}
}
}
let nodeLevel = 1;
function addItem(parentUL, branch, parentName) {
for (var key in branch) {
var item = branch[key].children;
let name = '';
if (parentName) {
name = parentName }
$item = $('<li>', {
id: key,
});
$item.append($('<input>', {
type: "checkbox",
id: 'smb',
name: key,
value: key,
"data-parent": name,
}));
$item.append($('<label>', {
for: key,
text: key
}));
parentUL.append($item);
nodeLevel++;
if (branch[key].children) {
var $ul = $('<ul>', {
class: 'ul-child',
style: 'display: none'
}).appendTo($item);
addItem($ul, item, branch[key].label);
} else {
nodeLevel = 1;
}
}
}
// On default load
$(document).ready(function(){
addItem($('#sb'), data);
$('input[type="checkbox"]').prop("checked", "true");
$('label').click(function(){
$(this).closest('li').children('ul').slideToggle();
});
$('input[type="checkbox"]').change(function(e) {
var checked = $(this).prop("checked"),
container = $(this).parent(),
siblings = container.siblings();
container.find('input[type="checkbox"]').prop({
indeterminate: false,
checked: checked
});
function checkSiblings(el) {
var parent = el.parent().parent(),
all = true;
el.siblings().each(function() {
let returnValue = all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
return returnValue;
});
if (all && checked) {
parent.children('input[type="checkbox"]').prop({
indeterminate: false,
checked: checked
});
checkSiblings(parent);
} else if (all && !checked) {
parent.children('input[type="checkbox"]').prop("checked", checked);
parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0));
checkSiblings(parent);
} else {
el.parents("li").children('input[type="checkbox"]').prop({
indeterminate: true,
checked: false
});
}
}
checkSiblings(container);
});
});
$(".save").click(function() {
var sbl1 = $('#sb li input:checked').not('#sb li ul li input:checked').not('#sb li ul li ul li input:checked').map(
function(x){
return $(this).val().replace(/(["'])/g, "\\$1");
}).get().join('\',\'');
console.log(sbl1)
});
.no-bullets {
list-style: none;
padding: 0;
margin: 0;
}
.ul-child {
list-style: none;
margin: 0 0 0 5px;
}
.selectBox {
position: relative;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#SelectOptions {
display: none;
border: 0.5px #7c7c7c solid;
background-color: #ffffff;
max-height: 300px;
overflow-y: scroll;
text-align: left;
}
#SelectOptions label:hover {
background-color: #1e90ff;
}
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./style.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="form-group col-sm-8">
<div class="selectBox" onclick="toggleCheckboxArea()">
<select class="form-select">
<option></option>
</select>
<div class="overSelect"></div>
</div>
<div id="SelectOptions">
<ul class="no-bullets">
<li id="All">
<input type="checkbox" name="selectAll" id="selectAll">
<label>All</label>
<ul class="ul-child" style="display:none;" id="sb">
</ul>
</li>
</ul>
</div>
</div>
<button class="save">Save</button>
<p id="demo"></p>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="./script.js"></script>
</body>
I am trying to turn the json data that is in the db variable into a nested list on the html page. Instead it is giving me a sort of ladder of each child node inserted into the child node before it. I can not figure out why it is not nesting correctly. What am i missing?
db = JSON.parse(`
{
"title": "Root",
"children": [
{
"title": "Child1",
"children": [
{"title": "Child1a"},
{"title": "Child1b"},
{"title": "Child1c"}
]
},
{
"title": "Child2",
"children": [
{"title": "Child2a"},
{"title": "Child2b"},
{"title": "Child2c"}
]
}
]
}
`);
function recurse(u, j) {
li = document.createElement('li');
ul = document.createElement('ul');
li.setAttribute('title', j.title);
li.appendChild(ul);
u.appendChild(li);
(j.children || []).forEach(c => {
recurse(ul, c);
});
}
recurse(document.getElementById('tree'), db);
* {
margin: 0;
}
li::before {
content: attr(title);
}
li:hover {
cursor: grab;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Scratch</title>
</head>
<body>
<ul id='tree'></ul>
</body>
</html>
You're referring to the same variables over and over because you're not re-declaring them in the function scope.
db = JSON.parse(`
{
"title": "Root",
"children": [
{
"title": "Child1",
"children": [
{"title": "Child1a"},
{"title": "Child1b"},
{"title": "Child1c"}
]
},
{
"title": "Child2",
"children": [
{"title": "Child2a"},
{"title": "Child2b"},
{"title": "Child2c"}
]
}
]
}
`);
function recurse(u, j) {
var li = document.createElement('li');
var ul = document.createElement('ul');
li.setAttribute('title', j.title);
li.appendChild(ul);
u.appendChild(li);
(j.children || []).forEach(c => {
recurse(ul, c);
});
}
recurse(document.getElementById('tree'), db);
* {
margin: 0;
}
li::before {
content: attr(title);
}
li:hover {
cursor: grab;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Scratch</title>
</head>
<body>
<ul id='tree'></ul>
</body>
</html>
Hey all I am using KendoListBox and needing to loop through it and remove the selected [checked] items once I un-check the full category.
let apiData = {
"object_list": [{
"Name": "facebook",
"Description": null,
"Id": "eb8cb0c8c32d1201bff30cf54S4f30889abb23f92b1f7",
"DocumentType": null,
"ProviderId": 2,
"Cat": "Social Networks"
}, {
"Name": "twitter",
"Description": null,
"Id": "732fe66cce4365bc5074384f09b34e787f3f3efe8b55",
"DocumentType": null,
"ProviderId": 2,
"Cat": "Social Networks"
}, {
"Name": "Google",
"Description": null,
"Id": "8b11d6f7b74bf71a7ddbc62dcfead27087e0f3e047e",
"DocumentType": null,
"ProviderId": 2,
"Cat": "Search Engines"
}]
};
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
check: onCheck,
dataSource: {
data: apiData,
schema: {
model: {
children: 'items'
},
parse: (data) => {
// The new data array to be used by treeview
let newData = [];
data.object_list.forEach(item => {
// Look for an already created parent for that categoty
let parent = newData.find(parentItem => parentItem.text === item.Cat);
// If not found...
if (!parent) {
// ... create a new one...
parent = {
id: 2,
text: item.Cat,
expanded: true,
items: [],
spriteCssClass: "folder"
};
// ... and add it to the final data array.
newData.push(parent);
}
// Add the new item to the parent
parent.items.push({
id: 3,
text: item.Name,
spriteCssClass: "image"
});
});
// Return the root object with its new child items
return [{
id: 1,
text: 'Categories',
expanded: true,
spriteCssClass: "rootfolder",
items: newData
}];
}
}
}
});
$("#Sources").kendoListBox();
function onCheck(e) {
let checkedNodes = [],
checkedNode = e.node.innerText,
intx = 0,
listBox = $("#Sources").data("kendoListBox");
//console.log(e.node.innerText);
if (e.node.ariaChecked == "false") {
console.log("Its just now been selected *REMOVED*");
var node = listBox.dataSource.get("twitter");
//let listBoxItem = listBox.dataItems().find(item => item.text === e.node.innerText);
let listBoxItem = listBox.dataItems().find(item => "twitter" === "twitter");
console.log("listbox item: ", listBoxItem);
var text = e.node.innerText;
var textSpliced = text.split("\n").slice(1);
if (textSpliced.length >= 1) {
$.each(textSpliced, function(tS) {
console.log("splice: ", textSpliced[tS]);
listBox.dataSource.remove(textSpliced[tS]);
});
} else {
/*
$("#Sources option").each(function(i){
alert($(this).text() + " : " + $(this).val());*/
//if (listBoxItem) {
//console.log("list: ", listBoxItem);
//listBox.dataSource.remove(listBoxItem);
//}
//}
// });
}
} else {
console.log("Its just now been selected *ADDED*");
listBox = $("#Sources").data("kendoListBox");
var text = e.node.innerText;
var textSpliced = text.split("\n").slice(1);
if (textSpliced.length >= 1) {
$.each(textSpliced, function(tS) {
console.log(textSpliced[tS]);
listBox.add({
text: textSpliced[tS],
value: textSpliced[tS]
});
});
} else {
listBox.add({
text: checkedNode,
value: checkedNode
});
}
}
}
#treeview .k-sprite {
background-image: url("../content/web/treeview/coloricons-sprite.png");
}
.rootfolder {
background-position: 0 0;
}
.folder {
background-position: 0 -16px;
}
.pdf {
background-position: 0 -32px;
}
.html {
background-position: 0 -48px;
}
.image {
background-position: 0 -64px;
}
#filterText {
width: 100%;
box-sizing: border-box;
padding: 6px;
border-radius: 3px;
border: 1px solid #d9d9d9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.common.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.rtl.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.default.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.mobile.all.min.css">
<script type="text/javascript" src="https://kendo.cdn.telerik.com/2021.1.330/js/angular.min.js"></script>
<script type="text/javascript" src="https://kendo.cdn.telerik.com/2021.1.330/js/jszip.min.js"></script>
<script type="text/javascript" src="http://cdn.kendostatic.com/2021.1.330/js/kendo.all.min.js"></script>
<div id="treeview"></div>
<select id="Sources"></select>
I can do this
listBox.dataItems().find(item => item.text === e.node.innerText)
And be able to delete any 1 checked item. But if its more than 1 I am unable to figure out what I am missing.
So I tried doing this:
var text = e.node.innerText;
var textSpliced = text.split("\n").slice(1);
if (textSpliced.length >= 1) {
$.each(textSpliced, function(tS) {
console.log("splice: ", textSpliced[tS]);
listBox.dataSource.remove(textSpliced[tS]);
});
} else {}
But of course that did not produce any results - did not delete the items in the kendoListBox.
Try this new approach:
let apiData = {
"object_list": [{
"Name": "facebook",
"Description": null,
"Id": "eb8cb0c8c32d1201bff30cf54S4f30889abb23f92b1f7",
"DocumentType": null,
"ProviderId": 2,
"Cat": "Social Networks"
}, {
"Name": "twitter",
"Description": null,
"Id": "732fe66cce4365bc5074384f09b34e787f3f3efe8b55",
"DocumentType": null,
"ProviderId": 2,
"Cat": "Social Networks"
}, {
"Name": "Google",
"Description": null,
"Id": "8b11d6f7b74bf71a7ddbc62dcfead27087e0f3e047e",
"DocumentType": null,
"ProviderId": 2,
"Cat": "Search Engines"
}]
};
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
check: onCheck,
dataSource: {
data: apiData,
schema: {
model: {
children: 'items'
},
parse: (data) => {
// The new data array to be used by treeview
let newData = [];
data.object_list.forEach(item => {
// Look for an already created parent for that categoty
let parent = newData.find(parentItem => parentItem.text === item.Cat);
// If not found...
if (!parent) {
// ... create a new one...
parent = {
id: 2,
text: item.Cat,
expanded: true,
items: [],
spriteCssClass: "folder"
};
// ... and add it to the final data array.
newData.push(parent);
}
// Add the new item to the parent
parent.items.push({
id: 3,
text: item.Name,
spriteCssClass: "image"
});
});
// Return the root object with its new child items
return [{
id: 1,
text: 'Categories',
expanded: true,
spriteCssClass: "rootfolder",
items: newData
}];
}
}
}
});
$("#Sources").kendoListBox();
function onCheck(e) {
let listBox = $("#Sources").data("kendoListBox"),
treeView = $("#treeview").data("kendoTreeView"),
selection = [],
getSelection = (items) => {
items.forEach(item => {
if (item.hasChildren) getSelection(item.items);
else if (item.checked) selection.push(item);
});
};
listBox.remove(listBox.items());
getSelection(treeView.dataSource.data());
if (selection.length) {
selection.forEach(item => {
listBox.add({
text: item.text,
value: item.value
});
});
}
}
#treeview .k-sprite {
background-image: url("../content/web/treeview/coloricons-sprite.png");
}
.rootfolder {
background-position: 0 0;
}
.folder {
background-position: 0 -16px;
}
.pdf {
background-position: 0 -32px;
}
.html {
background-position: 0 -48px;
}
.image {
background-position: 0 -64px;
}
#filterText {
width: 100%;
box-sizing: border-box;
padding: 6px;
border-radius: 3px;
border: 1px solid #d9d9d9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.common.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.rtl.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.default.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2021.1.330/styles/kendo.mobile.all.min.css">
<script type="text/javascript" src="https://kendo.cdn.telerik.com/2021.1.330/js/angular.min.js"></script>
<script type="text/javascript" src="https://kendo.cdn.telerik.com/2021.1.330/js/jszip.min.js"></script>
<script type="text/javascript" src="http://cdn.kendostatic.com/2021.1.330/js/kendo.all.min.js"></script>
<div id="treeview"></div>
<select id="Sources"></select>
I have 2 jstree.
from 1st tree i am sending selectd nodes to 2nd tree.
on back button I am deleting entry of 2nd tree with its id but it doesnot works but it fetches all the selected records.
here is my code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
html { margin:0; padding:0; font-size:62.5%; }
body { font-size:14px; font-size:1.4em; }
h1 { font-size:1.8em; }
.demo { overflow:auto; border:1px solid silver; min-height:100px;min-width: 400px;float: left }
.demo1 { overflow:auto; border:1px solid silver; min-height:100px;min-width: 400px; float: right}
</style>
<link rel="stylesheet" href="style.min.css" />
</head>
<body><div id="frmt" class="demo"></div>
<div id="frmt1" class="demo1"></div>
<script>
var arrayCollection = [ {"id": "animal", "parent": "#", "text": "Animals"}, {"id": "device", "parent": "#", "text": "Devices"}, {"id": "dog", "parent": "animal", "text": "Dogs"}, {"id": "lion", "parent": "animal", "text": "Lions"}, {"id": "mobile", "parent": "device", "text": "Mobile Phones"}, {"id": "lappy", "parent": "device", "text": "Laptops"}, {"id": "daburman", "parent": "dog", "text": "Dabur Man", "icon": "/"}] ;
</script>
<script>
function refreshJSTree() {
$('#frmt1').jstree(true).settings.core.data = arrayCollection;
$('#frmt1').jstree(true).refresh();
}
</script>
<script>
function deleteNode() {
console.log("Delete : "+$('#frmt1').jstree("get_checked"));
arrayCollection = arrayCollection.pop($('#frmt1').jstree("get_checked"));/*
.filter(function(el) {
return el.id !== $('#frmt1').jstree("get_checked");
});*/
refreshJSTree();
}
</script>
<script>
function callGraph() {
var akn=$('#frmt').jstree("get_checked");
var c = akn + "";
var spl = c.split("!");
var dt = "";
var cnt = spl.length - 1;
arrayCollection=[];
var temp=[];
console.log("SPL : "+spl);
for(q=0;q<cnt;q++)
{
if (spl[q].startsWith(","))
{
var xp=spl[q].split(",")[1];
if(xp.startsWith("OU") || spl[q].startsWith("DC"))
temp.push(xp);
}
else if(spl[q].startsWith("OU") || spl[q].startsWith("DC"))
{
temp.push(spl[q].split(",")[0]);
}
}
console.log("TEMP : "+temp);
/*for(q=0;q<cnt;q++)
{
var test=0;
for(m=0;m<temp.length;m++)
{
var textData=spl[q]+"";
console.log(temp[m]);
if(textData.Contains(temp[m]))
test=1;
}
if(test==0)
{
if (spl[q].startsWith(","))
arrayCollection.push(spl[q].split(",")[1]);
else
arrayCollection.push(spl[q].split(",")[0]);
}
}*/
for (q = 0; q < cnt; q++) {
if (spl[q].startsWith(","))
dt=/*spl[q].split(",")[1]//*/dt ={"id":spl[q].split(",")[1],"text":spl[q].split(",")[1]}
else
dt=/*spl[q].split(",")[0]//*/dt = {"id": spl[q].split(",")[0] ,"text": spl[q].split(",")[0] };
arrayCollection.push(dt);
}
refreshJSTree();
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jstree.min.js"></script>
<button onclick="callGraph()">>></button>
<button onclick="deleteNode()"><<</button>
<script>
$('#html').jstree();
$('#frmt').jstree({
'core': {
'data':<%= session.getAttribute("PATH")%>
},
"checkbox": {
"whole_node": false,
"keep_selected_style": true,
"three_state": true,
"tie_selection": false
}, "search": {
"fuzzy": true
}, "plugins": ["checkbox", "search"]
});
$('#frmt1').jstree({
'core': {
'data':[{"text":"DC TEST"}]
},
"checkbox": {
"whole_node": false,
"keep_selected_style": true,
"three_state": true,
"tie_selection": false
}, "search": {
"fuzzy": true
}, "plugins": ["checkbox", "search"]
});
/*$('button').on('click', function () {
a = $('#frmt').jstree("get_checked");
callGraph(a);
// window.location = "read.jsp?name="+a;
});*/
</script>
</body>
</html>
I have a JSON file which contains data like the following:
{"posts": [
{ "title":"1", "url":"n1.png" },
{ "title":"2", "url":"n2.png" },
{ "title":"3", "url":"n3.png" },
{ "title":"4", "url":"n4.png" },
{ "title":"5", "url":"n5.png" },
{ "title":"6", "url":"n6.png" },
{ "title":"7", "url":"n7.png" },
{ "title":"8", "url":"n8.png" },
{ "title":"9", "url":"n9.png" },
{ "title":"10", "url":"n10.png" }
]}
I need to filter title by range with two text boxes: from and to.
Why not do this?
var json = JSON.parse('{"posts": [
{ "title":"1", "url":"n1.png" },
{ "title":"2", "url":"n2.png" },
{ "title":"3", "url":"n3.png" },
{ "title":"4", "url":"n4.png" },
{ "title":"5", "url":"n5.png" },
{ "title":"6", "url":"n6.png" },
{ "title":"7", "url":"n7.png" },
{ "title":"8", "url":"n8.png" },
{ "title":"9", "url":"n9.png" },
{ "title":"10", "url":"n10.png" }
]}');
var filteredJson = json.posts.filter(function (row) {
if(row.title matches your criteria) {
return true
} else {
return false;
}
});
Yes, its an ES5 method but that can be shimmed quite nicely
I use Linq JS on my current project and it works really well for filtering data.
http://jslinq.codeplex.com/
var posts = [
{ "title":"1", "url":"n1.png" },
{ "title":"2", "url":"n2.png" },
{ "title":"3", "url":"n3.png" },
{ "title":"4", "url":"n4.png" },
{ "title":"5", "url":"n5.png" },
{ "title":"6", "url":"n6.png" },
{ "title":"7", "url":"n7.png" },
{ "title":"8", "url":"n8.png" },
{ "title":"9", "url":"n9.png" },
{ "title":"10", "url":"n10.png" }
];
var filteredPost = JSLINQ(posts)
.Where(function(item){ return item.title >= "textBox1Value" && item.title <= "textBox2Value"; });
There is another solution to this: using jLinq.js (documentation), which has even more features. In this case, you can get the solution by using the following code:
var selectedPosts = jLinq.from(posts)
.betweenEquals("title",4,8)
.select();
try this
var q = new RegExp(req.query.q,'i');
posts = posts.filter(function(item){
if(item.title.match(q) || item.url.match(q)){
return item;
}
});
Read the json into an object/arr the parseJson function of jquery(http://api.jquery.com/jQuery.parseJSON/) and the try to splice the array using the splice function() Just make a copy of the object and splice that one.
Well i have this JSON array full of projects, each of project belong to a product:
[
{
"id": 1,
"parentProduct": {
"id": 12,
"productName": "Test 123"
},
"phase": "Phase 4",
"productNumber": "111223",
"projectName": "Test JPEG Apple",
"supplier1": "de",
},
{
"id": 2,
"parentProduct": {
"id": 12,
"productName": "Test from me"
},
"phase": "222",
"productNumber": "11122",
"projectName": "Test PNG",
"supplier1": "222"
}
]
I wanted to get only those with specific parent id, and i did it as below:
filterByProductId(projects, productId) : any[] {
var filteredArray = new Array;
for(var k in projects) {
if(projects[k].parentProduct.id == productId) {
filteredArray.push(projects[k]);
}
}
return filteredArray;
}
json data array of objects filter
<html>
<head>
<script type="text/javascript">
/*
var ss = JOSN.stringify(obj,function(key,value){ //serialization
if(key=='a'){
return undefined;
}else{
return value;
}
});
*/
var jsonStr = [
{
"name": "Bang Bang",
"outline": "A chance encounter with a mysterious charmer leads to a bank employee's wild adventure.",
"rating": 5.6,
"director": "Siddharth Anand",
"id": 250
},
{
"name": "Bang Bang",
"outline": "A chance encounter with a mysterious charmer leads to a bank employee's wild adventure.",
"rating": 5.6,
"director": "Siddharth Anand",
"id": 250
},
{
"name": "Bang Bang",
"outline": "A chance encounter with a mysterious charmer leads to a bank employee's wild adventure.",
"rating": 5.6,
"director": "Siddharth Anand",
"id": 250
},
{
"name": "Indian",
"outline": "After his daughter's tragic death, a freedom fighter steps up his war against corruption.",
"rating": 8.4,
"director": "Shankar",
"id": 251
},
{
"name": "Dilwale Dulhania Le Jayenge",
"outline": "Raj and Simran meet on a trip to Europe. After some initial misadventures, they fall in love. The battle begins to win over two traditional families.",
"rating": 8.4,
"director": "Aditya Chopra",
"id": 253
}
];
var jsonobj = jsonStr;
function filterMovieDirectorData(movie,director){
if(movie!='' && (director!='' && director!='Director')){
var data = jsonobj.filter(function(item){
return (item["name"].toLowerCase().indexOf(movie.toLowerCase())!=-1 && item["director"].toLowerCase().indexOf(director.toLowerCase())!=-1)
});
}else if(movie!='' && director=='Director'){
var data = jsonobj.filter(function(item){
return item["name"].toLowerCase().indexOf(movie.toLowerCase())!=-1
});
}else if(movie=='' && (director!='' && director!='Director')){
var data = jsonobj.filter(function(item){
return item["director"].toLowerCase().indexOf(director.toLowerCase())!=-1
});
}
return data;
}
function getFilterDirectorJson(){
var inputStr = document.getElementById("movie").value;
var e = document.getElementById("director");
var directorStr = e.options[e.selectedIndex].text;
if( (inputStr=='' || inputStr=='Enter movie name') && (directorStr=='' || directorStr=='Director') ){
alert("Please enter movie name or select director.");
document.getElementById("filter_data_div").innerHTML="";
document.getElementById("movie").focus();
return false;
}
var filterObjs = filterMovieDirectorData(inputStr,directorStr);
var text="";
for(var i=0; i<filterObjs.length; i++){
text+='<div id="filter_data"><div><h3>'+filterObjs[0].name+'</h3></div>';
text+='<div>Director : '+filterObjs[0].director+'</div></div><div class="clear"></div>';
}
if(filterObjs.length===0){document.getElementById("filter_data_div").innerHTML='<div id="filter_data"><div><h3>No movies found.</h3></div></div>';}else
document.getElementById("filter_data_div").innerHTML=text;
}
window.onload=function(){
getDirectors();
}
function getDirectors(){
for(var i=0; i<jsonobj.length; i++){
//console.log(jsonobj[i].director);
var option = document.createElement("option");
option.text = jsonobj[i].director;
option.value = i;
var daySelect = document.getElementById('director');
daySelect.appendChild(option);
}
}
</script>
<style>
#director{
line-height: 3px;
padding: 20px;
font-size: 21px;
color: #acacac;
}
#go{
background: #FFC000;
padding: 11px 14px 16px 11px;
font-size: 36px;
line-height: 3;
color: #fff;
margin: 0px;
text-align: center;
}
#movie{
width: 213px;
font-size: 21px;
margin-left: 12px;
padding: 20px;
color:#ACACAC;
}
#main_div{
background: #EEEEEE;
width: 554px;
min-height:120px;
}
#filter_data{
width: 335px;
background: #D8D8D8;
padding: 1px 0px 20px 13px;
margin: 20px 0px 0px 12px;
border: 1px solid #000;
}
a{text-decoration:none;}
.clear{clear: both;}
</style>
</head>
<body>
<div id="main_div">
<div style="display:block;">
<input type="text" id="movie" placeholder="Enter movie name">
<select id="director" ><option value="">Director</option></select>
Go
</div>
<div id="filter_data_div"></div>
</div>
</body>
</html>
First once you have all the json data, you need to traverse them. For that,
**$.each(data, function (i, data) {
if (data.title >= "textBox1Value" && item.title <= "textBox2Value")
//then the data;
});**
List item