Delete Entry from jstree does not works - javascript

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>

Related

Nested List from Javascript

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>

Kendo UI ListBox removal depending on treeview check

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>

How to Gather & Parse JSON Data in HTML

I'm ultimately looking to create a HTML file that will accomplish the following tasks. The point is, I need it to be all inclusive in an HTML snippet/file.
Make a GET api call to a backend CMS (ie: Drupal). This api call returns the following JSON data for a specific content item:
{
"jsonapi": {
"version": "1.0",
"meta": {
"links": {
"self": {
"href": "http://jsonapi.org/format/1.0/"
}
}
}
},
"data": {
"type": "node--espot_html",
"id": "fbaab7dd-09c2-4aa0-852d-4b9462074a45",
"attributes": {
"drupal_internal__nid": 1,
"drupal_internal__vid": 11,
"langcode": "en",
"revision_timestamp": "2019-10-31T13:29:29+00:00",
"revision_log": null,
"status": true,
"title": "Razor Hero Image",
"created": "2019-10-28T16:24:20+00:00",
"changed": "2019-10-31T13:29:29+00:00",
"promote": true,
"sticky": false,
"default_langcode": true,
"revision_translation_affected": true,
"path": {
"alias": "/razor-hero",
"pid": 1,
"langcode": "en"
},
"body": {
"value": "<div class=\"jns-hero-image jns-hero-image-message-left\" id=\"hero_slideshow\"><img alt=\"Clean Shave\" data-entity-type=\"file\" data-entity-uuid=\"fbc875d0-ef17-4813-981c-22a29e42c44f\" src=\"/sites/default/files/inline-images/dont-shave-2.jpg\" />\r\n<div class=\"grid-container\">\r\n<div class=\"grid-x grid-padding-x\">\r\n<div class=\"small-12 medium-8 cell hero-message\">\r\n<div>\r\n<h1 class=\"text-hero text-hero-left\">Get a Much Better<br />\r\nShave</h1>\r\n\r\n<p>Fewer things look and feel better than a clean shave!</p>\r\n<a>SHOP NOW</a></div>\r\n</div>\r\n</div>\r\n</div>\r\n</div>\r\n",
"format": "full_html",
"processed": "<div class=\"jns-hero-image jns-hero-image-message-left\" id=\"hero_slideshow\"><img alt=\"Clean Shave\" data-entity-type=\"file\" data-entity-uuid=\"fbc875d0-ef17-4813-981c-22a29e42c44f\" src=\"/sites/default/files/inline-images/dont-shave-2.jpg\" /><div class=\"grid-container\">\n<div class=\"grid-x grid-padding-x\">\n<div class=\"small-12 medium-8 cell hero-message\">\n<div>\n<h1 class=\"text-hero text-hero-left\">Get a Much Better<br />\nShave</h1>\n\n<p>Fewer things look and feel better than a clean shave!</p>\n<a>SHOP NOW</a></div>\n</div>\n</div>\n</div>\n</div>\n",
"summary": ""
}
},
"relationships": {
"node_type": {
"data": {
"type": "node_type--node_type",
"id": "837a5cbe-f8fe-4c03-a613-2092dff1168e"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/node_type?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/node_type?resourceVersion=id%3A11"
}
}
},
"revision_uid": {
"data": {
"type": "user--user",
"id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/revision_uid?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/revision_uid?resourceVersion=id%3A11"
}
}
},
"uid": {
"data": {
"type": "user--user",
"id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/uid?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/uid?resourceVersion=id%3A11"
}
}
}
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45?resourceVersion=id%3A11"
}
}
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45"
}
}
}
I'm then looking for the JSON response to be parsed to extract the only the data under the "value": object.
I need to have the escape characters removed
The end result should be that the HTML (shown below) is rendered in the browser:
<div class="jns-hero-image jns-hero-image-message-left" id="hero_slideshow"><img alt="Clean Shave" data-entity-type="file" data-entity-uuid="fbc875d0-ef17-4813-981c-22a29e42c44f" src="/sites/default/files/inline-images/dont-shave-2.jpg" /><div class="grid-container"><div class="grid-x grid-padding-x"><div class="small-12 medium-8 cell hero-message"><div><h1 class="text-hero text-hero-left">Get a Much Better<br />Shave</h1><p>Fewer things look and feel better than a clean shave!</p><a>SHOP NOW</a></div></div></div></div></div>"
If processed successfully, this is what should display on the webpage:
Screenshot if image rendered via HTML
Here is the HTML I have tried. My apologies for breaking etiquette, I was not aware this would be perceived as such. In my browsers console it tells me the forEach is not a valid function or this response.
'<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ghibli App</title>
<link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet" />
<!-- <link href="style.css" rel="stylesheet" /> -->
</head>
<body>
<div id="root"></div>
<script>
const app = document.getElementById('root');
const container = document.createElement('div');
container.setAttribute('class', 'container');
app.appendChild(logo);
app.appendChild(container);
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(value => {
const card = document.createElement('div');
card.setAttribute('class', 'card');
const h1 = document.createElement('h1');
h1.textContent = valuable.title;
const p = document.createElement('p');
value.description = value.description.substring(0, 300);
p.textContent = `${value.description}...`;
container.appendChild(card);
card.appendChild(h1);
card.appendChild(p);
});
} else {
const errorMessage = document.createElement('marquee');
errorMessage.textContent = `Gah, it's not working!`;
app.appendChild(errorMessage);
}
}
request.send();
</script>
</body>
</html>'
This ended up producing the end result that I was looking to produce:
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
<script>
const app = document.getElementById('root');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let obj = JSON.parse(this.responseText);
console.log(obj.data.attributes.body.value)
app.innerHTML = obj.data.attributes.body.value.replace('src="/sites','src="http://localhost:4700/sites');
}
};
xmlhttp.open("GET", "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45", true);
xmlhttp.send();
</script>
</body>
</html>

change background of list item based on json lookup

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/

Removing the Item from the dropdown once its added using angular

HTML Code
<!doctype html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>
document.write("<base href=\"" + document.location + "\" />");
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1> NG options</h1>
<form name="addUser">
Application:
<select ng-model="filterAddUser.application" ng-init ="filterAddUser.application = 'STACK'" title="" ng-options="value as value for (key , value) in applicationStatus">
</select>
Roles:
<select ng-model="filterAddUser.role" title="" ng-init ="filterAddUser.role = 'R'" ng-options="role.value as role.param for role in roleStatus">
</select>
<button ng-click="addToCart()">AddItem</button>
<div class="addCart">
<ul ng-repeat="item in items">
<li><b>Application:</b> {{item.application}}</li>
<li><b>Role:</b> {{item.role}}</li>
<li class="actionOptions">
<button ng-click="toggleSelected($index)">removeItem</button>
</li>
</ul>
</div>
</form>
</body>
</html>
Javascript Code
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [];
$scope.applicationStatus = {
"TEST App": "TEST",
"ABC App": "ABC",
"TRY App": "TRY",
"SIR App": "SIR",
"LOPR App": "LOPR",
"STACK App": "STACK"
};
$scope.roleStatus = [{
"param": "Read",
"value": "R"
}, {
"param": "Write",
"value": "W"
}, {
"param": "Admin",
"value": "A"
}, {
"param": "Super Approver",
"value": "SA"
}, {
"param": "Supervisor",
"value": "S"
}];
$scope.addToCart = function() {
$scope.items.push({
application: $scope.filterAddUser.application,
role: $scope.filterAddUser.role
});
// Clear input fields after push
$scope.filterAddUser['application'] = "";
$scope.filterAddUser['role'] = "";
}
$scope.toggleSelected = function(index) {
$scope.items.splice(index, 1);
};
});
All that i am trying to do is when i add the application to the cart that application needs to be removed from the dropdwon and also when i click on the remove item that needs to be pushed back to the cart i have included a plunker as well http://plnkr.co/edit/kSsetX?p=preview
need help on the same.
Updated your plunkr: http://plnkr.co/edit/QQobh7Jx76r7lDzw7TzV
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [];
var deletedApplication = [];
$scope.applicationStatus = {
"TEST App": "TEST",
"ABC App": "ABC",
"TRY App": "TRY",
"SIR App": "SIR",
"LOPR App": "LOPR",
"STACK App": "STACK"
};
$scope.roleStatus = [{
"param": "Read",
"value": "R"
}, {
"param": "Write",
"value": "W"
}, {
"param": "Admin",
"value": "A"
}, {
"param": "Super Approver",
"value": "SA"
}, {
"param": "Supervisor",
"value": "S"
}];
$scope.filterAddUser = {
application: $scope.applicationStatus[0],
role: $scope.roleStatus[0]
};
$scope.addToCart = function() {
deletedApplication.push([
$scope.filterAddUser.application, $scope.applicationStatus[$scope.filterAddUser.application]
]);
delete $scope.applicationStatus[$scope.filterAddUser.application];
$scope.items.push({
application: $scope.filterAddUser.application,
role: $scope.filterAddUser.role
});
// Clear input fields after push
$scope.filterAddUser['application'] = $scope.applicationStatus[0];
$scope.filterAddUser['role'] = $scope.roleStatus[0];
}
$scope.toggleSelected = function(index) {
var addApp = deletedApplication.filter(function(deletedApp){
return deletedApp[0] === $scope.items[index].application;
})[0];
$scope.applicationStatus[addApp[0]] = addApp[1];
console.log($scope.applicationStatus);
$scope.items.splice(index, 1);
};
});

Categories

Resources