For some reason, I cannot get my global variable counter to increase, even when it increases within the function I have the count++ occurring in. My outputted results are different between the text outputted within the function and the text outside of it. Any idea what I am doing wrong here? Shouldn't the count increase on each iteration of the survey.oncomplete function results?
Survey
.StylesManager
.applyTheme("modern");
var kn2 = "LwrHXqFRN_pszCopTKHF_Q"
var kn3 = "exroCUoYl4wVzs7pKU_49w"
var count = 0
var keyname = ("kn" + count)
var mapilink = "https://images.mapillary.com/" + (keyname) + "/thumb-1024.jpg";
var json = {
pages: [
{
name: "page1",
elements: [
{
type: "image",
name: "image",
imageLink: (mapilink),
imageHeight: 580,
imageWidth: 640
},
{
type: "html",
name: (keyname),
visible: false,
html: (keyname)
},
{
type: "rating",
name: "Walkability",
title: "How walkable does this look to you"
},
{
type: "rating",
name: "Saftey",
title: "How safe does this look to you"
},
{
type: "rating",
name: "Comfortability",
title: "How comfortable does this look to you"
}
]
}
]
}
window.survey = new Survey.Model(json);
var username = document.getElementById("user").value;
survey
.onComplete
.add(function (result) {
count ++;
var PID = document.getElementById("user").value;
var results = PID + "_" + (keyname) + ":\n" + JSON.stringify(result.data, null, 3) + (count) ;
document
.querySelector('#surveyResult')
.textContent = results;
survey.clear();
survey.render();
});
$("#surveyElement").Survey({model: survey});
Got an answer from a seperate stackexchange post - basically, I needed to wrap everything in more functions.
function outputting function text rather than expected output
Related
I know this has been asked before, but my case seems to be little bit different
I have two js files, one for logic, one for objects which includes data about movie(s)
my first file looks like this
var movieTitle = document.getElementById("movieTitle");
var rating = document.getElementById("rating");
var movieYear = document.getElementById("movieYear");
var movieDuration = document.getElementById("movieDuration");
var actorName = document.getElementById("actorName");
var actorRole = document.getElementById("actorRole");
var actorNameI = document.getElementById("actorName2");
var actorRoleII = document.getElementById("actorRole2");
var testClick = document.getElementById("testClick");
var movie = movieI;
movieTitle.innerHTML = "Title: " + movie.title;
movieYear.innerHTML = "release Year: " + movie.releaseYear;
movieDuration.innerHTML = "Duration: " + movie.duration;
actorName.innerHTML = "Name: " + movie.actors[0].name;
actorRole.innerHTML = "Role: " + movie.actors[0].role;
actorNameI.innerHTML = "Name: " + movie.actors[1].name;
actorRoleII.innerHTML = "Role: " + movie.actors[1].role;
rating.innerHTML = "Rating: " + movie.rating;
testClick.addEventListener("click", function(){
var movie = movieII
})
file from where i fetch objects looks like this
var movieI = {
title: "Titanic",
releaseYear: 1997,
rating: "PG21",
duration: "3 hours",
actors: [
{
name: "leonardo dicaprio",
role: "role goes here"
},
{
name: "kate winslet",
role: "role goes here"
},
]
};
var movieII = {
title: "Wolf of wall street",
releaseYear: 2013,
rating: "PG18",
duration: "2H 30M",
actors: [
{
name: "leonardo dicaprio",
role: "role goes here"
},
{
name: "jonah hill",
role: "role goes here"
},
]
};
on my first js file i have following function
testClick.addEventListener("click", function(){
movie = movieII
})
this is supposed to modify value of movie variable and set it to movieII so it can switch/access second object(movieII) from my objects file, but it does not seem to be working.
Your problem is that updating the object doesn't change what has already been shown in the HTML, you need to update your HTML with the new information but only after it changed in the variable.
You can do that linear ( as you have in your code) or just creating a function that you can call every time and will help you avoiding duplicated code.
Here is one way you can do that:
//Titanic
let movieI = {
title: "Titanic",
releaseYear: 1997,
rating: "PG21",
duration: "3 hours",
actors: [
{
name: "leonardo dicaprio",
role: "role goes here"
},
{
name: "kate winslet",
role: "role goes here"
},
]
};
let movieII = {
title: "Wolf of wall street",
releaseYear: 2013,
rating: "PG18",
duration: "2H 30M",
actors: [
{
name: "leonardo dicaprio",
role: "role goes here"
},
{
name: "jonah hill",
role: "role goes here"
},
]
};
let actorsBox = document.getElementById("actos-box");
let movieTitle = document.getElementById("movieTitle");
let rating = document.getElementById("rating");
let movieYear = document.getElementById("movieYear");
let movieDuration = document.getElementById("movieDuration");
let actorName = document.getElementById("actorName");
let actorRole = document.getElementById("actorRole");
let actorNameI = document.getElementById("actorName2");
let actorRoleII = document.getElementById("actorRole2");
let testClick = document.getElementById("testClick");
let movie = movieI;
updateMovie();
testClick.addEventListener("click", function(){
movie = movieII
updateMovie();
})
function updateMovie(){
movieTitle.innerHTML = "Title: " + movie.title;
movieYear.innerHTML = "release Year: " + movie.releaseYear;
movieDuration.innerHTML = "Duration: " + movie.duration;
actorName.innerHTML = "Name: " + movie.actors[0].name;
actorRole.innerHTML = "Role: " + movie.actors[0].role;
actorNameI.innerHTML = "Name: " + movie.actors[1].name;
actorRoleII.innerHTML = "Role: " + movie.actors[1].role;
rating.innerHTML = "Rating: " + movie.rating;
}
Also I highly recommend you not to use var as it can do weird things you might not want to do.
Take a look at this for learning more about let variables.
Have you try to use function and parameters for this project?
Here was the docs
Function in js
I have this huge slickgrid that users can fill with data. once filled in the data is sent to the server-side with AJAX and then to the database with PHP. then I get the data out of the database and put it inside a PHP array. Now how do I populate the slickgrid with that array data. I cant seem to find the solution to this. because How to I get that php array inside the javascript slickgrid file.
javascript slickgrid for information:
<script type ='text/javascript'>
var gridArray;
var editedRows = []
function CreateColumns() {
var columns = [
{id: "hours", name: "uren", field: "hours"},
{id: "Total_inspection", name: "totaal inspectie", field: "Total_inspection", editor: Slick.Editors.Integer},
{id: "Per_hour_inspection", name: "Per uur", field: "Per_hour_inspection"},
{id: "Total_losses", name: "Totaal uitstoot", field: "Total_losses",editor: Slick.Editors.Integer},
{id: "Per_hour_losses", name: "Per uur", field: "Per_hour_losses"},
{id: "%_spil", name: "% Spil", field: "%_spil"},
{id: "%_cumul", name: "% Cumul", field: "%_cumul"},
{id: "Operator", name: "Operator", field: "Operator",editor: Slick.Editors.Text},
{id: "SKU", name: "SKU", field: "SKU",editor: Slick.Editors.Text},
{id: "End_SKU", name: "Tellerstand einde SKU", field: "End_SKU"},
{id: "Batch", name: "Batch", field: "Batch"}
];
return columns;
}
function CreateOptions() {
var options = {
editable: true,
enableCellNavigation: true,
enableColumnReorder: false,
autoEdit :false
};
return options;
}
var data = [];
function CreateData() {
for (var i = 0; i < 8; i++) {
data[i] = {
hours: 6+i+"U",
};
}
return data;
}
console.log(data)
function CreateGrid(elementId) {
if (!gridArray) { gridArray = []; }
var data = CreateData();
//editedRows.push(data)
var grid = new Slick.Grid("#" + elementId,data, CreateColumns(), CreateOptions());
gridArray[length] = grid;
//todo tets localstorage
var columnidx = data[0].Total_inspection
var columnidx2 = data[0].Total_losses
var calculation = columnidx2/columnidx
var columnidx3 = data[0].Per_hour_inspection
//push(calculation)
var columnid = data[columnidx]
//console.log(calculation,columnidx3)
grid.onCellChange.subscribe(function (e,args) {
//console.log('arguments',args.item);
editedRows.push(args.item)
console.log('arrayrows',editedRows)
});
}
console.log(editedRows)
$('#Savebtn').click(function () {
console.log(editedRows);
//var UpdatedRows = JSON.stringify(editedRows);
//console.log(UpdatedRows);
$.ajax({
type: "POST",
url: "request.php",// changed
data: {arrayOfValues: editedRows},
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
alert(data)
console.log(data)
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
PHP looks like this :
$stmt = $mysqli->prepare("SELECT * FROM kicdata");
//$stmt->bind_param('i',$id);
$stmt->execute();
$result = $stmt->get_result();
$return_data = [];
while($row = $result->fetch_assoc()){
$return_data[]= $row;
}
var_dump($return_data);
UPDATE: the use of ajax solved the part to send the server-side array to the client-side.
I wanted to break down paragraph based on it’s entityRanges.
So the actual paragraph looks like this,
{
type: 'paragraph',
depth: 1,
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
entityRanges: [{
type: 'LINK',
offset: 83,
length: 16,
data: {
target: '_self',
url: '/index.htm'
}
}]
}
But my expected results should be like below,
{
type: 'paragraph',
depth: 1,
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
entityRanges: [{
type: 'LINK',
offset: 83,
length: 16,
data: {
target: '_self',
url: '/index.htm'
}
}],
embbeded: [{
type: 'text',
text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our '
}, {
type: 'link',
text: 'customer support',
data: {
target: '_self',
url: '/index.htm'
}
}, {
type: 'text',
text: 'page.'
}]
}
I wanted to break down the text into multiple parts based on it’s offset & length values.
As per the example, customer support is the offset value.
So it should breakdown in the below order
Do you have questions or comments and do you wish to contact ABC?
Please visit our
customer support
page.
All above parts needs to pushed to new object embbeded.
I hope that I understood you correctly:
const data = {
"text": "Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.",
"entityRanges": [{
"type": "LINK",
"offset": 83,
"length": 16,
"data": {
"target": "_self",
"url": "/index.htm"
}
},
{
"type": "LINK",
"offset": 7,
"length": 4,
"data": {
"target": "_self",
"url": "/index.htm"
}
}
]
};
function breakData(data) {
let {
entityRanges,
text
} = data;
const result = [];
let finalPart = '';
let index = 0;
entityRanges
.sort((a, b) => a.offset - b.offset)
.forEach((styleRange) => {
const {
offset,
length,
type,
data
} = styleRange;
const firstPart = text.substring(index, offset);
result.push({
type: 'text',
text: firstPart,
});
index = offset + length; // + 1;
const secondPart = text.substring(offset, index);
result.push({
type,
data,
text: secondPart,
});
finalPart = text.substring(index);
});
if (finalPart) {
result.push({
type: 'text',
text: finalPart,
});
}
data.embbeded = result;
return data;
}
const result = breakData(data);
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';
Apologies if this has been answered before, I have checked other answers and can't work it out from those.
I have a set of information that I would like placed into an array named "teamDetails". Here is the relevant /post item from server.js:
app.post('/create', (req, res) => {
console.log('Post command received');
console.log(req.body);
console.log(req.body.data.teamDetails[0]);
//We need to push the variable below, 'teamDetails', as an object into an array of the same name
var teamDetailsObj = {
// Modified for Postman
"teamName": req.body.data.teamDetails[0].teamName,
"teamNameShort": req.body.data.teamDetails[0].teamNameShort,
"teamfounded": req.body.data.teamDetails[0].teamFounded,
"teamHome": req.body.data.teamDetails[0].teamHome
};
console.log(teamDetails);
var newTeam = new Team({
"data.added": new Date(),
"data.entry": req.body.data.entry
});
newTeam.save().then((doc) => {
console.log("This is newTeam.data: " + newTeam.data);
console.log("This is teamDetailsObj: " + teamDetailsObj);
newTeam.data.teamDetails.push(teamDetailsObj);
var teamId = doc.id;
res.render('success.hbs', {teamId});
console.log("Team Added - " + teamId);
}, (e) => {
res.status(400).send(e);
});
});
Here is my team.js model:
var mongoose = require('mongoose');
var ObjectID = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var Schema = mongoose.Schema;
var Team = mongoose.model('Team', {
data: {
entry: {
type: String,
default: "USER.INPUT"
},
added: {
type: Date,
default: Date.Now
},
teamDetails: [
{
teamName: {
type: String,
trim: true,
required: true,
default: "First Team"
},
teamNameShort: {
type: String,
trim: true,
uppercase: true,
maxlength: 3,
required: true
},
teamFounded: {
type: Number,
maxlength: 4
},
teamHomeCity: {
type: String
}
}
]
}
});
module.exports = {Team};
Lastly, the sample data I'm trying to inject via Postman:
{
"data": {
"entry": "Postman.Entry",
"teamDetails": [
{
"teamName": "Test Teamname",
"teamNameShort": "TTN",
"teamFounded": "1986",
"teamHome": "London",
"players": [
{
"player1Name": "Test Player 1",
"player1Position": "Forward",
"player1Nationality": "GBR"
},
{
"player2Name": "Test Player 2",
"player2Position": "Defender",
"player2Nationality": "UKR"
},
{
"player3Name": "Test Player 3",
"player3Position": "Goaltender",
"player3Nationality": "IRL",
"captain": true
}
],
"coachingStaff": {
"headCoach": "Derp McHerpson",
"teamManager": "Plarp McFlarplarp"
}
}
]
}
}
(Disregard the players section, it's another kettle of fish)
As a result of using my code above, the resulting entry for teamDetails is just an empty array. I just can't get my code to push the teamDetailsObj into it.
Any help anyone can provide is appreciated.
It looks like you add teamObjDetails AFTER saving it with newTeam.save().then( ... )
I'm not a lot familiar with Mongoose but I don't see how could the team details could be present if not added before saving.
Let me know if it changes something !
A. G
I'm trying to iterate over some JSON that I have included in my file and everything seems to be working fine up until I want to add my icons into each stakebox icon div. Any idea what might be going wrong? I want to add one icon if the value of my JSON object === true and one if the value === false.
$.each(stakeBox, function (i, stakeBoxData) {
var jsonDate = stakeBoxData.data_change_date;
var winLoss = stakeBoxData.win;
var points = stakeBoxData.amount_stakebox;
var winLoss = stakeBoxData.win;
var id = stakeBoxData.id;
if (stakeBoxDay < jsonDate) {
var self = $(this);
console.log(this.win);
$('.stakebox-container').append('\
<div id="' + id + '" class="stakebox-message-container">\
<div id="stakebox-icon"></div>\
<div><h5 id="stakebox-game"></h5></div>\
<div><h5 id="stakebox-points">' + points + '</h5></div>\
</div>\
');
if (this.win === true) {
$('#stakebox-icon').append('<i class="far fa-smile face"></i>');
} else {
$('.stakebox-message-container').css('background', '#a20000');
$('#stakebox-icon').append('<i class="far fa-frown face"></i>');
};
// console.log(i);
} else {
// console.log('nope');
}
});
Here is some of the JSON for reference:
var stakeBox = [{
id: "1",
amount: "40.00",
user_id: "1",
amount_stakebox: "33",
win: true,
data_change_date: "20180229",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}, {
id: "2",
amount: "1.00",
user_id: "1",
amount_stakebox: "4124124",
win: false,
data_change_date: "20180429",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}];