I followed this below link :
https://codepen.io/templarian/pen/VLKZLB
But here when clicking More Option, I have to get the dynamic populated Names like
var Obj = [{name:"1st Item",taste:"sweet"},{name:"2nd item",taste:"spicy"}];
Replace of "Alert Cost" and "Alert Player Gold".
I tried but I am failed to get in dynamic looping.
You can do like this.... Add this code inside the function inside demo controller.
$scope.arr = [];
for(let x of [{name:"1st Item",taste:"sweet"},{name:"2nd item",taste:"spicy"}]) {
let newArr = [];
newArr.push(x.name);
newArr.push(function ($itemScope) {
alert($itemScope.item.cost);
});
$scope.arr.push(newArr);
}
And then replace the old array of Alert Cost" and "Alert Player Gold" with $scope.arr.
$scope.menuOptions = [
['Buy', function ($itemScope) {
$scope.player.gold -= $itemScope.item.cost;
}],
null,
['Sell', function ($itemScope) {
$scope.player.gold += $itemScope.item.cost;
}, function ($itemScope) {
return $itemScope.item.name.match(/Iron/) == null;
}],
null,
['More...', $scope.arr]
];
Voila, you good to go.
Here is working codepen example. Working example https://codepen.io/anon/pen/jGBJMY?editors=1010
Related
I have a .aspx file working on SharePoint.
We are using IE11, jQuery 2.2.3, jQuery UI 1.11.4, Bootstrap 3.3.6
We had this system for around three years by a third party, which we stopped business. And not able to contact anymore.
It was working fine until a few weeks ago suddenly the page is loading forever and showing this error
SCRIPT5007: Unable to get property 'toLowerCase' of undefined or null reference
Loading page - capture
I have Googled and it seems like the script is waiting for ConfigurationCube.js to load. But since it's not loading, I think it's waiting forever.
/* handles the displaying of all outstanding items requiring approval*/
var TableCreated=0;
var app="";
var teamsArr = [];
var GlobalDivisionsArr = [];
$(document).ready(function(){
//check to see if the Configuration cube Obj Exists and wait until it does
var checkExist = setInterval(function() {
if (sessionStorage["ConfigurationCube"] != null) {
app = JSON.parse(sessionStorage.ConfigurationCube).AppURL;
/**CreateLookupSectionForEmployees("My Winners","Kaizen List","#ViewWinnersTable");**/
//Displayed using the configuration cube.js file
DisplayUserInformation();
popDD("kznSearchCategory",JSON.parse(sessionStorage.ConfigurationCube).ListOfCategories);
IntialPopulationOfApprovedKaizens("","Kaizen List","#kznSearchResultsTable");
//Initialize date range picker
/**$("#kznEditToDate").datepicker();*/
var CubeMin = (JSON.parse(sessionStorage.ConfigurationCube).SubmissionPeriod).split(" ")[0];
clearInterval(checkExist);
}
}, 500);
});
I also tried in IE8, 9, 10, Edge. All not working.
Our company does not allow Chrome or any other browser so we need to get it work in IE..
My current meta tag is like this. Also tried various ways, but did not work.
<meta http-equiv="x-ua-compatible" content="IE=edge; charset=UTF-8">
Does anyone have any similar problems?
Any kind of idea is appreciated..
When clicking on the error, it directs to ConfigutationCube.js
//Tools for other pages
function compareStrings(a, b) {
// Assuming you want case-insensitive comparison
a = a.toLowerCase();
b = b.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
Script snip from SearchKaizen.js
function IntialPopulationOfApprovedKaizens(HeadingTitle,ListName,ElementToAppend){
//Get all current data from lists
var GetKaizenPromise = GetList( "Kaizen List",
"Id,Nominated_x0020_person, Status, Kaizen_x0020_Title,Division/Id, Team/Id,Division/Title, Team/Title, Name, Financial_x0020_Year, Kaizen_x0020_Category,Quarter",
"Division/Id, Team/Id,Division/Title, Team/Title",
"Status eq 'Approved'",
app);
$.when(GetKaizenPromise).done(function(KaizenSelectionData){
var EditButton = "";
var Results = KaizenSelectionData.d.results;
//Creates table structure and heading
var DataTableHtml = "";
var SetVotedBackground = "style='background-color:lightgreen;color:white;'";
var DivisionList = [];
var TeamList = [];
var YearList = [];
var DivisionCheck = [];
var TeamCheck = [];
if(Results.length > 0){
for(r=0;Results.length > r;r++){
TableCreated++;
var ResultsName = Results[r].Nominated_x0020_person;
var KaizenTitle = Results[r].Kaizen_x0020_Title;
var ResultsTeam = Results[r].Team.Title;
var ResultsDivision = Results[r].Division.Title;
var ResultsTeamId = Results[r].Team.Id;
var ResultsDivisionId = Results[r].Division.Id;
var ResultsCategory = Results[r].Kaizen_x0020_Category;
var ResultsStatus = Results[r].Status;
var ResultsQuarter = Results[r].Quarter;
var ResultsYear = Results[r].Financial_x0020_Year;
EditButton = "<p style='cursor:pointer;' class='edititem text-light-blue' data-itemid='"+Results[r].Id+"' data-listname='"+ListName+"'><i class='fa fa-edit'></i> View</p>";
DataTableHtml += "<tr>"+
"<td>"+ResultsName+"</td><td>"+ResultsDivision+"</td><td>"+ResultsTeam +"</td>"+
"<td>"+ResultsYear+"</td><td>"+ResultsQuarter+"</td><td>"+KaizenTitle +"</td>"+
"<td>"+ResultsCategory +"</td><td>"+EditButton+"</td>"
"</tr>";
//Create the drop down box info from all the results
if($.inArray(ResultsDivision , DivisionCheck ) == -1){
// Add to departments list
DivisionList.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
DivisionCheck.push(ResultsDivision);
//Keep duplicate of original divisions list
GlobalDivisionsArr.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
}
if($.inArray(ResultsTeam , TeamCheck) == -1){
// Add to Teams list
TeamList .push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
TeamCheck.push(ResultsTeam);
//Keep duplicates of original list
teamsArr.push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
}
if($.inArray(ResultsYear , YearList) == -1){
// Add to Year list
YearList.push(ResultsYear );
}
//next Item
}
}else{
//if there are no results
DataTableHtml = "<tr>"+
"<td colspan='8'>No results found</td>" +
"</tr>";
}
YearList.sort();
YearList.reverse();
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
popDD("kznSearchYear",YearList);
popDDSearchWithDataAttr("kznSearchTeam",TeamList,TeamList);
DivisionList.unshift({"FullName": "All","ID":"All"}); //Add All option to division list
popDDVal("kznSearchDivision",DivisionList);
//adds items to DOM
$(ElementToAppend + " tbody").html(DataTableHtml);
//Create column match with returned results
if (Results.length>0){
$.fn.dataTable.ext.errMode = 'console';
$(ElementToAppend).DataTable({
"dom": 'ftipr',
"responsive": true
});
}
$("body").css("overflow","");
//removes overlayer and loading symbol
$("#OverlayFade").addClass("hidden");
$("#Timer").addClass("hidden");
});
}
This snip of the script has popDDVal, and it looks like 'DivisionList' 'TeamList' 'YearList' is returning null. Since this is null it can not break from the loading overlayer.
I was able to narrow it down to this part.
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
Changed it to this, and it worked. But obviously the sorting is not sorted correctly, but least it works now...
TeamList.sort();
DivisionList.sort();
Instead of passing in an anonymous function pass the function name:
TeamList.sort(compareStrings);
or
DivisionList.sort(compareStrings);
I am trying to dynamically add an object with values from an input field to the end of an array using JavaScript. The only catch is that I'm trying to do it with an input field. Here's what I want to happen:
The user types in something in a text field
My program already adds a unique ID for it
Add it to the end of an array in the form of a object
Keep on adding objects to that array
This is what I want in my JSON file:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, {
"id": 1,
"description": "Task #2 Description"
}, {
"id": 3,
"description": "Task #3 Description"
}]
}
What I am currently getting is:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, ]
}
Every time I add a new Task, it replaces the one that is already there.
Here is my JavaScript code:
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.onclick = function() {
id = indentification++;
description = content.value;
var task = {
list: []
}
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
I would really appreciate it if anyone could help me out. I've spent hours trying to figure it out. Thanks!
The problem is here:
var task = {
list: []
}
task.list.push({id, description});
Each time you do this your list become empty then add new item.
change to this
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
var task = {
list: []
}
submit.onclick = function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8"); // what're you doing here, browser do not allow write file to disk
}
There are a couple of things that you need to consider here:
Form submit must be refreshing the page and resetting your global variables. Thus you need to prevent default action on click of submit.
(as mentioned in earlier answers) The list is being initiated on every click. You will need to initialize the variable task outside the onClick function
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
//initialize outside the on click function
var task = {
list: []
}
submit.onclick = function(e) {
//This prevents page refresh on form submission and preserves the global variable states
e.preventDefault();
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
This should hopefully solve your problem.
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.addEventHandler("click", function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
This is my code. i am using $localStorage for pushing an object into array. when i clicking the button the object is pushed properly and splicing the same same object again click on the same button. $localStorage.tableArray assign to the $scope.Storage for dropdown list. Drop down list coming good when the button action done.
My problem is the $scope.$storage having two items. if i refresh the page dropdown list not came.
if i pushing or splicing action performed on the buttons drop down list coming good.
please help how to get $scope.$storage items into the dropdown list when refreshing the page.
I Create a plunker regarding this. check once
HTML:
<body ng-controller="MainCtrl">
<a class="btn {{table.btnClass}} btn-success" ng-repeat="table in tablelist" ng-click="getTable(table)" style="padding-left:1px">{{table.tablename}}</a>
<select ng-options="table.tablename as table.tablename for table in $storage" ng-model="table.tablename"><option value="">---select table---</option></select>
JS:
var app = angular.module('plunker', ["ngStorage"]);
app.controller('MainCtrl', function ($scope,$localStorage,$filter) {
$scope.tablelist = [{ "tablename": "t1" }, { "tablename": "t2" },{ "tablename": "t3" },{ "tablename": "t4" }]
if ($localStorage.tableArray === undefined) {
$localStorage.tableArray = []
}
if ($localStorage.tableslist === undefined) {
$localStorage.tableslist = []
}
angular.forEach($scope.tablelist, function (list, $index) {
var found = $filter('filter')($localStorage.tableArray, { tablename: list.tablename }, true);
if (found.length) {
$scope.tablelist[$index].btnClass = found[0].btnClass;
}
});
$scope.getTable = function (table) {
table.btnClass = table.btnClass == "btn-danger" ? "btn-success" : "btn-danger"
var exists = false;
angular.forEach($localStorage.tableArray, function (list, $index) {
if ((list.tablename == table.tablename)) {
console.log(list.tablename)
console.log(table.tablename)
exists = true;
$localStorage.tableArray.splice($index, 1)
$localStorage.tableslist.splice($index, 1)
$scope.$storage= $localStorage.tableArray;
console.log( $scope.$storage)
return false
}
});
if (!exists) {
$localStorage.tableslist.push(table)
$localStorage.tableArray = $localStorage.tableslist;
$scope.$storage = $localStorage.tableArray
console.log($localStorage.tableArray)
table.color = "red"
}
}
});
https://plnkr.co/edit/0RpAGVR5ZpVFMvmmxipu?p=preview
As per my understanding you want your dropdown list to be initialized on refresh with the stored value from your localstorage.
Adding below line in controller works for me:
$scope.$storage = $localStorage.tableArray
Check plnkr
I need to split an array into an JSON array which should be following pattern.
{{"url":url, "north":True "side":True}, {"url":url, "north":False, "side":True}}
I get the url parameter with this code. As you can see here, this code displays 3 checkboxes where you can select if the picture is north, on the side or if you want to select it.
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
xmlDoc = xmlHttp.responseXML;
pictureTemp = [document.getElementById("imgfilename")];
$('.login-form').append('<button onclick="sendAuswahl()">Send</button><br>');
for (var i = 0; i < xmlDoc.getElementsByTagName("imgfilename").length; i++) {
pictureTemp[i] = xmlDoc.getElementsByTagName("imgfilename")[i].childNodes[0].nodeValue;
$('.login-form').append('<input type="checkbox" name="north" value="North"><input type="checkbox" name="orientation" value="Side"><input type="checkbox" name="url" value='+ pictureTemp[i]+'><img src='+ pictureTemp[i]+' width="50%"></br>');
};
}
To get all ticked checkboxes, I use this code:
var arrayUrl = $("input[name='url']:checked").map(function(){
return this.value;
}).get()
var arrayNorth = $("input[name='north']:checked").map(function(){
return "True";
}).get()
var arrayOrientation = $("input[name='orientation']:checked").map(function(){
return "True";
}).get()
To convert the selection to a JavaScript object and to get the pattern which I described above, I use this:
var picture = {
"url" : arrayUrl,
"North" : arrayNorth,
"Side" : arrayOrientation
};
But when I alert the value of a selected image I get this:
{"url":http://www.example.com, "north":True "side":True}
And when I select 2 images I get this:
{"url":http://www.example.com, http://www.example2.com, "north":True "side":False}
Instead of this:
{{"url":http://www.example.com, "north":True "side":False}, {"url":http://www.example2.com, "north":False, "side":True}}
So my question is now: How can I adept the values in the pattern which I've described above?
var picture = [];
$.each(arrayUrl, function(index,val) {
val = {
"url" : val,
"North" : arrayNorth[index],
"Side" : arrayOrientation[index]
};
picture.push(val);
});
var picture = [];
$(arrayUrl).each(function(index) {
picture.push({
"url": arrayUrl[index],
"North": arrayNorth[index],
"Side": arrayOrientation[index]
});
});
I'm new to JS. I'm trying to delete the parent node with all the children by clicking a button. But the console tells me that undefined is not a function. What am I missing?
Fiddle:
http://jsfiddle.net/vy0d8bqt/
HTML:
<button type="button" id="output">Get contacts</button>
<button type="button" id="clear_contacts">clear contact</button>
<div id="output_here"></div>
JS:
// contact book, getting data from JSON and outputting via a button
// define a JSON structure
var contacts = {
"friends" :
[
{
"name" : "name1",
"surname" : "surname1"
},
{
"name" : "name2",
"surname" : "surname2"
}
]
};
//get button ID and id of div where content will be shown
var get_contacts_btn = document.getElementById("output");
var output = document.getElementById("output_here");
var clear = document.getElementById("clear_contacts");
var i;
// get length of JSON
var contacts_length = contacts.friends.length;
get_contacts_btn.addEventListener('click', function(){
//console.log("clicked");
for(i = 0; i < contacts_length; i++){
var data = contacts.friends[i];
var name = data.name;
var surname = data.surname;
output.style.display = 'block';
output.innerHTML += "<p> name: " + name + "| surname: " + surname + "</p>";
}
});
//get Children of output div to remove them on clear button
//get output to clear
output_to_clear = document.getElementById("output_here");
clear.addEventListener('click', function(){
output_to_clear.removeNode(true);
});
You should use remove() instead of removeNode()
http://jsfiddle.net/vy0d8bqt/1/
However, this also removes the output_to_clear node itself. You can use output_to_clear.innerHTML = '' if you like to just delete all content of the node, but not removing the node itself (so you can click 'get contacts' button again after clearing it)
http://jsfiddle.net/vy0d8bqt/3/
You want this for broad support:
output_to_clear.parentNode.removeChild(output_to_clear);
Or this in modern browsers only:
output_to_clear.remove();
But either way, make sure you don't try to remove it after it has already been removed. Since you're caching the reference, that could be an issue, so this may be safer:
if (output_to_clear.parentNode != null) {
output_to_clear.remove();
}
If you were hoping to empty its content, then do this:
while (output_to_clear.firstChild) {
output_to_clear.removeChild(output_to_clear.firstChild);
}
I think using jQuery's $.remove() is probably the best choice here. If you can't or don't want to use jQuery, The Mozilla docs for Node provides a function to remove all child nodes.
Element.prototype.removeAll = function () {
while (this.firstChild) { this.removeChild(this.firstChild); }
return this;
};
Which you would use like:
output_to_clear.removeAll();
For a one-off given the example provided:
while (output_to_clear.firstChild) { output_to_clear.removeChild(output_to_clear.firstChild); }