Good day everyone,
I've been grinding the whole day yesterday at this function however I've been running in circles and would
appreciate any input or suggestions.
Currently I want to create a onclick function on my div (match-tab) that when it gets clicked it will send it's value to my javascript which will let the function know which game's data it should render.
at the moment my function looks like this:
for (x in data){
var recent_matches_row_one = document.getElementById('recent-matches-row-one');
var recent_matches_row_two = document.getElementById('recent-matches-row-two');
var col = document.createElement("div");
col.className = "col no-padding";
var matchTab = document.createElement("div");
matchTab.className = "match-tab";
matchTab.id = "match-tab";
matchTab.value = x;
matchTab.innerHTML = ++x;
matchTab.onclick = foo(this.value);
if (x < 15){
recent_matches_row_one.appendChild(col);
col.appendChild(matchTab);
} else if (x > 15) {
recent_matches_row_two.appendChild(col);
col.appendChild(matchTab);
}
}
}
function foo(value){
var v = value;
console.log(v);
}
As you can see the recent matches functions renders the amount of match tabs according to the amount of match data available.
The front end looks like this and as you can see it is seen as undefined.
I would really like to write this whole application in vanilla JavaScript since I'm new to it and want to learn it before moving to other frameworks and libraries.
Thanks
So the answer to my question was is the fact that I had to change matchTab.onclick = foo(x); to matchTab.onclick = function(){foo(this.value)}; this allowed me to get the value assigned in my JavaScript. Thanks for all the input!
Related
First, let me explain what I'm trying to do: I want to make a script for a video game that counts how much money is in the game, and create an element to display it. The tracking the money part was easy, but apparently making elements is like the most confusing thing i've tried to do yet.
Lightshot screenshot of chrome console: https://prnt.sc/shszc2
The blue-highlighted line in the screenshot gave an error after being executed twice. I boxed the error message in red.
I'll take some code out of the script I have, mainly aiming for code that is important for the issue i want help with, leaving out code that I understand.
Also note that I am extremely new to generating graphics in Javascript, so if my ways of making elements are horrendous, then it's because I just kept trying random crap until something seemed to work and stuck with whatever that was.
// The elements that I created. Again i know next to nothing about elements, so the only thing that I
// know will work is this catastrophe.
var initialDiv = document.getElementById('onecup');
mainText = initialDiv.appendChild(document.createElement('mainText'));
mainText.style.position = 'absolute';
mainText.style.left="50%";
mainText.style.top="64px"
mainText.style.width = "290px";
mainText.style.height = "160px";
mainText.style.color = "white";
mainText.style.zindex = 1;
mainText.style.fontSize = "18px"
trackerBack = mainText.appendChild(document.createElement('trackerBack'));
trackerBack.style.position = 'absolute';
trackerBack.style.left="-200px"
trackerBack.style.top="0px"
trackerBack.style.width = "400px";
trackerBack.style.height = "160px";
trackerBack.style.backgroundColor = "black";
trackerBack.style.opacity = ".20"
trackerBack.style.zindex=1;
diffTotal = trackerBack.appendChild(document.createElement('diffTotal'));
diffTotal.id = "diffTotal"
diffTotal.style.position = 'absolute';
diffTotal.style.top="20%"
diffTotal.style.left="40%";
diffTotal.style.color = "rgba(255,255,255,255)";
diffTotal.style.opacity = "1"
diffTotal.style.zindex = 2;
diffTotal.style.fontSize = "30px"
diffFielded = diffTotal.appendChild(document.createElement('diffFielded'));
diffFielded.id = "diffFielded"
diffFielded.style.position = 'absolute';
diffFielded.style.top="-15px"
diffFielded.style.left="0px";
diffFielded.style.color = "rgba(255,255,255,255)";
diffFielded.style.opacity = "1"
diffFielded.style.zindex = 2;
diffFielded.style.fontSize = "20px"
// This function is used by a latter function to set the values of the text elements. I initially didn't
// have this but thought adding it would help, but nothing changed.
// By the way, "toBna2" stands for to "big number abbreviation". It doesn't do anything major, besides
// shrink down numbers. Tried removing it, problem still persists.
conductValues = function(targetName, targetAssignment) {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
// This looping function controls the values that the elements display. However, I removed the code that
// tells the function what values to make the elements, so if you want to test it, I guess just define
// the 4 values as anything or make your own.
findValueDiff = setInterval(function() {
// If i make one of these lines a comment, it works, regardless of which one it is. But if i let both of
// them run, the second document.getElementById("elementId") returns as null. Always the second one.
conductValues("diffTotal", (aValP + aValU - bValP - bValU))
conductValues("diffFielded", (aValU - bValU))
}
I even tried doing this:
conductValues = function(targetName, targetAssignment) {
if (document.getElementById(targetName) != "undefined") {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
}
But all that does is make the function fail on the first attempt, because always the second document.getElementById("elementId") returns as null.
I'm not entirely sure if I included enough information, but I don't know what else to add so hopefully I did. But if you need more information, just ask and i'll try to edit this post as swiftly as possible.
Thanks to all responders, and I hope you stay healthy as you have fun coding.
Edit 1: Thought i would get something different if I set the entity's variables one at a time like this:
conductValues = function(targetName, targetAssignment) {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
loopMode=0
findValueDiff = setInterval(function() {
if (loopMode == 0) {
conductValues("diffTotal", (aValP + aValU - bValP - bValU))
loopMode = 1
} else {
conductValues("diffFielded", (aValU - bValU))
loopMode = 0
}
}, 1000
);
But the problem still hasn't changed. Second time it tries to update, it fails.
Ah, I got it:
diffTotal = trackerBack.appendChild(document.createElement('diffTotal'));
diffFielded = diffTotal.appendChild(document.createElement('diffFielded'));
conductValues("diffTotal", (aValP + aValU - bValP - bValU))
conductValues("diffFielded", (aValU - bValU))
conductValues = function(targetName, targetAssignment) {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
Those are the lines, which cause the error.
diffFielded is a child of diffTotal. In the first conductValues call, you replace the innerHTML of diffTotal. When you are doing this, you are removing diffFielded, because it's replaces by the new value and then it cannot by found anymore because it does not exist anymore.
I assume diffFielded should actually be another child of trackerBack, so you should do:
diffFielded = trackerBack.appendChild(document.createElement('diffFielded'));
Tip:
Move the style stuff into a css file.
I have a problem with Qualtrics Loop and Merge + Javascript. Basically, Qualtrics reload the previous trial of my loop instead of a new one.
First, here is what I try to do: I have two sets of pictures, at each loop, one picture of each set is randomly picked and displayed (randomly to the left or right side). At the end of the loop, each pictures of the set will be displayed (33 in each set, so 33 trials of the loop), without picking twice the same picture. At each trial, I also display randomly the name of the condition "in relationship" or "friends"
The problem in details:
I have coded something that seems to work quite well, except at some point: It happens that when loading the next trial of the loop, it doesn't display new pictures but instead the one that were presented in the previous trial (and also the same name of condition). This can go for a while presenting me always the same pictures, or this can just be one time.
In any case, this trial which is represented count as a trial, as my loop always ends after 33 trials, whatever if some of these are actually not new pictures presented.
This problem doesn't appear always at the same trial, and can appear several times in a loop.
It also happened that only one picture displayed is new, and the other is the one presented in the previous trial. (I really don't get how this can happen).
I coded the randomisation of picture in an empty question, just before the question where it displays the pictures. This empty question is supposed to not require to press the "next" button. When the trial are correct, this is working well, but when the next trial is going to be one "reloaded" trial, it requires to press the "next" button.
I tried the survey with Firefox and Edge, and the problem is the same.
My javascript code:
In the first question of the survey:
Qualtrics.SurveyEngine.addOnload(function () {
function shuffle(o) { //v1.0
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var FacesM_list = "IM_7U04c3TQlA7dT3D,IM_eE5iBcKfoOblbJH,IM_a3mklzA9E1OuRWl,IM_bQnoSJOGwa0vn9P,IM_5inNCVgPdHHTVSR,IM_bHlurQJWSXDRDFj,IM_3rCr2DIzW2cvqLP,IM_509x1wz7pM6PP0N,IM_3UGdsp02IcCqaSV,IM_eLrY7bwDPiT7apn,IM_3LdlHnBb6tnkBEh,IM_3pY6z6JDgaDvwq1,IM_9HtZxBS79DiOfR3,IM_03c9pDSpcwcqIyF,IM_6WGKJOzUWK4TJat,IM_2rxQPEGO7SEvsY5,IM_9YN3UCUtWEWTfGR,IM_8jZTSUAGJfuVECV,IM_9nQkFhRY2cLIVgN,IM_2abcJA7B79jt30h,IM_cD31N8XPTGliUN7,IM_0eL8iQd4PVdyuQl,IM_cuOoV9gSAe6CWd7,IM_9Nv3X7lWYEsTzsF,IM_5ccXAuuomEEyamp,IM_9mnvThFiNA5U84t,IM_e3UGNNuMdrKH8cl,IM_3aggsd5P9MMlUDr,IM_4ORY6GEMW8CmNPT,IM_50WOBkz8ADTFGHH,IM_3rqtlVBfijYCccZ,IM_3CzDsr0tYv7PH5H,IM_4SmeprjDgOeCl5b"
var FacesF_list = "IM_6fkHDs5f6ItAuk5,IM_0ri9MLjDhHxyonP,IM_bKlHtoAaxnBFlnT,IM_1WUqtBPpdhERpjf,IM_ac0yWos8tAqSMNT,IM_3xCePACn1Lq97tH,IM_6o1ZPLGUM682Au1,IM_babATdN3VtBLIsl,IM_8HSUICLvFvDXaN7,IM_0ebTztq3ML5Zh0V,IM_3lB8j5dhMs8i8ip,IM_0iC0pwDlpOkcTGt,IM_cIRojwU6sx3W7Od,IM_9ZHNbignrAfcThX,IM_8iFXvVcCqk5hemN,IM_6rrwImdl4Nss0u1,IM_6mPEaoIdazwqAWp,IM_b8lrxhsPGcc1HaR,IM_23uYWeF2gYVMsap,IM_6ycfrm5xOlewjFb,IM_7UKValFGc9Kmpp3,IM_8Bbkzsmc7CyMvqt,IM_d5S95FnSgo8j06F,IM_brXT4VUU8QJiRwN,IM_9MEkpgEmOwXhril,IM_6KG9qokOlD16GDH,IM_ellgVnYbtb8ZSbb,IM_eg6qSYMQ56z5JpX,IM_5vfbDNPdZeP1XCZ,IM_cDbOprwCUUSnUZT,IM_cumIGHXOFByV4Pz,IM_0jh2Va4JTfGsQDz,IM_0CGlFRy4dW8lDcF"
var FacesM_order = [];
for (var i = 1; i <= 33; i++) {
FacesM_order.push(i);
}
FacesM_order = shuffle(FacesM_order);
var FacesF_order = [];
for (var i = 1; i <= 33; i++) {
FacesF_order.push(i);
}
FacesF_order = shuffle(FacesF_order);
var nTrial = 0;
Qualtrics.SurveyEngine.setEmbeddedData("FacesM_order", FacesM_order.toString());
Qualtrics.SurveyEngine.setEmbeddedData("FacesF_order", FacesF_order.toString());
Qualtrics.SurveyEngine.setEmbeddedData("FacesF_list", FacesF_list.toString());
Qualtrics.SurveyEngine.setEmbeddedData("FacesM_list", FacesM_list.toString());
Qualtrics.SurveyEngine.setEmbeddedData("nTrial", nTrial.toString());
});
And in the first question of the Block with Loop and Merge:
Qualtrics.SurveyEngine.addOnload(function () {
var nTrial = Number("${e://Field/nTrial}") + 1;
var FacesF_list = "${e://Field/FacesF_list}".split(',');
var FacesM_list = "${e://Field/FacesM_list}".split(',');
var FacesF_order = "${e://Field/FacesF_order}".split(',');
var FacesM_order = "${e://Field/FacesM_order}".split(',');
var FacesF = FacesF_list[FacesF_order[nTrial]];
var FacesM = FacesM_list[FacesM_order[nTrial]];
var rand = Math.random()
if (rand < 0.5) {
var left = FacesF
var right = FacesM
} else {
var left = FacesM
var right = FacesF
}
Qualtrics.SurveyEngine.setEmbeddedData("nTrial", nTrial.toString());
Qualtrics.SurveyEngine.setEmbeddedData("left", left.toString());
Qualtrics.SurveyEngine.setEmbeddedData("right", right.toString());
this.clickNextButton.delay(.00000000000001);
});
Thanks a lot for your help!
I'm trying to clone a div after a user puts in the amount of divs to be cloned. User will put in a number (say 3) and the function will create three group-container divs. The prompt works, but nothing happens after that. Seems pretty simple but it's evading me. Is my logic incorrect? Obviously my programming skills are very new.
I create a function that has the input (groupInput)
Create a for loop to reiterate the following instruction
The for loop will clone group-container as many times as i<groupInput
function addGroup() {
var groupInput = prompt("How many groups? 1-100");
for(i=0; i<groupInput; i++){
var group = document.getElementById("group-container");
var clone = group.cloneNode(true);
group.parentNode.appendChild(clone);
}
}
Any suggestions would be much appreciated.
Updated
Thanks for the suggestions, I get I should use class for this now.
I did get it to work with the ID in jsfiddle (not sure why it's not in my html), but now with the class it's not: https://jsfiddle.net/waynebunch/c5sw5dxu/. getElementsByClassName is valid right?
You should put the group declaration outside of the for loop so the clone remains the same throughout the loop.
Fiddle
function addGroup() {
var groupInput = prompt("How many groups? 1-100");
var group = document.getElementById("group-container");
for(i=0; i<groupInput; i++){
var clone = group.cloneNode(true);
group.parentNode.appendChild(clone);
}
}
The prompt() method probably returns the correct number, but with type set to String. Instead try
parseInt(groupInput)
To convert the value to a number, which should allow the for loop to execute properly.
Something like the below might work once you get your quantity in from a prompt or text input.
var doc = document;
var input = prompt("Please enter your qty", "0");
if (input != null) {
for (i = 0; i < input; i++) {
var elem = doc.createElement('div');
elem.className = 'group-container';
}
}
(This is my first javascript project, so the solution may be obvious to more experienced people, but it's not to me!)
I am trying to code the input from three drop down lists. The context is helping people assess whether they meet the criteria for disability assistance.
The first drop-down asks whether a person can stand at all or not
(yes/no)
The next asks how far they can walk (choose from a range of
distances
The third asks whether they need any aids or adaptations
(no/yes)
Depending on how far they can walk they get a score: 12 is the maximum. However if a person can't stand they automatically get 12 points. also, depending on whether they need any aids and adaptations can affect the scoring.
The intention is therefore to have an if-then-else function (if to respond to person unable to stand, else if to create output dependent on walking distance and need for adaptations, and else to create output based purely on walking distance.
Everything works fine if until i include the adaptations drop down. the problem is that to do this i need to create a variable based on the value returned from the 'distance walked' function. at this point the console returns 'Uncaught TypeError: getdistancescore is not a function'.the coding has no problem recognising getdistancescore until i do this
here's the coding: (the line that causes the problems is marked "//this is the problem"
//stand-yes-no
var standYN =[];
standYN["mp1"]=0;
standYN["mp2"]=1;
function getstandYN(){
var standscore=0;
var theForm = document.forms["mobilityform"];
var standscore = theForm.elements["mobp1"];
getstandYN = standYN[standscore.value];
return getstandYN;
}
//end standyes-no
//distances
var distances = [];
distances["mp3"]=0;
distances["mp4"]=4;
distances["mp5"]=8;
distances["mp6"]=12;
distances["mp7"]=12;
//note mp5 could be 10
function getdistancescore(){
var distancescore=0;
var theForm = document.forms["mobilityform"];
var distancescore = theForm.elements["mobp2"];
getdistancescore = distances[distancescore.value];
return getdistancescore;
}
//end distances
//needs aid or appliance yes-no
var aiappYN =[];
aiappYN["mp1"]=0;
aiappYN["mp2"]=1;
function getaiappYN(){
var aiappscore=0;
var theForm = document.forms["mobilityform"];
var aiappscore = theForm.elements["mobp3"];
getaiappYN = aiappYN[aiappscore.value];
return getaiappYN;
}
//end needs aids or appliance yes-no
//CALCULATION STARTS
var ai_appscore = getaiappYN()
var standingscore = getstandYN();
//THIS IS THE PROBLEM
var walkingdistance = getdistancescore();
//END THIS IS THE PROBLEM
if (standingscore == 1){
var actualscore = 12
}
//extra 'else if' to go here
else {
var actualscore = getdistancescore();
}
//CALCULATION ENDS
//display results
var divobj = document.getElementById("score");
divobj.innerHTML="Total Score "+actualscore;
var divobj = document.getElementById("check");
divobj.innerHTML="Check "+standingscore;
}
Apologies if i haven't explained this very well, and for the length of the question. I've searched on a wide range of help sites but can't find anything that explains what's happening
Do you see what you're doing with getstandYN here ?
function getstandYN(){
var standscore=0;
var theForm = document.forms["mobilityform"];
var standscore = theForm.elements["mobp1"];
getstandYN = standYN[standscore.value];
return getstandYN;
}
getstandYN is a function, then in the middle of the function you reassign it to standYN[standsore.value]
Notice what happens here
function foo() {
foo = 5;
return foo;
}
foo(); // 5
foo(); // Uncaught TypeError: foo is not a function
console.log(foo); // "5"
I have the following script where a variable gets its value from an input field, however when I run my function its not working, returns nothing. Im new to JS so im unsure if it needs to be part of a function *even though Ive tried this with no luck) or what...
/////////////////////////////////////////////////////////////////////
// Variables
// Content/SLA
var ContentMinutes = '';
var ContentMinutesSelector; // Switch Case
var ServiceLevel = 5;
var NoOfFrames = 2;
// Render Time (Hairier the Better)
var AvgFrameRenderTime = '';
var AvgFrameRenderTimeSelector = 10; // Switch Case
var CoresInTest = document.getElementById('CoresInTest').value;
// Other
var EstimatedCoreHours = NoOfFrames * CoresInTest * AvgFrameRenderTimeSelector;
// Cost Estimate
var CostEstimate = ServiceLevel * EstimatedCoreHours;
/////////////////////////////////////////////////////////////////////
// Functions
function CalculateEstimate() {
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").innerHTML=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").innerHTML=EstimatedCoreHours.toFixed( 2));
}
my PriceEstimate and EstimatedCoreHours fields are both just empty divs, <div id="EstimatedCoreHours"></div>, My calculations work if i define a value for the variable as opposed to document.getElementById so I believe I must need to run a function or something to update all the vartiables?
But if I set...
var CoresInTest = document.getElementById('CoresInTest').value;
to
var CoresInTest = 10;
Then it works fine...
Its not actually my return, the problem is my variables arent calling, IF i define them with a number then it works.
I guess you need to do something like this, if you are looking to get calculated data in your div.
document.getElementById("PriceEstimate").innerHTML=parseInt(CostEstimate.toFixed(2));
// Estimate Core Hours
document.getElementById("EstimatedCoreHours").innerHTML=parseInt(EstimatedCoreHours.toFixed(2));
If var CoresInTest = 10; works fine, then your code is placed wrong.
What element is CoresInTest? is it a text field? and if so is this script placed or called before the element renders? then you will have to reinitialize that variable.
If PriceEstimate and EstimatedCoreHours are elements you should use the value property
this might work for you:
document.getElementById("PriceEstimate").value=parseInt(CostEstimate.toFixed(2),10);
document.getElementById("EstimatedCoreHours").value=parseInt(EstimatedCoreHours.toFixed(2),10);
If var CoresInTest = 10; makes it work fine, then it must be something to do with document.getElementById('CoresInTest').value - so why isn't that working? Is it a drop down list? Instead of us guessing, tell us.