Javascript not recognising function - javascript

(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"

Related

Demanding multiple coordinates from an undefined amount of elements

Firstly I would like to give you an example, of what exactly I am talking about, and afterwards what I found out/different problems.
I would like to ask for every element, here points (they do share a class) with a diameter of 1 px. To simplify it, I thought of putting it inside an array. The amount of these points is undefined, there may be 2 or 100.
Afterwards i would like to store the x and y coordinates, which I get with the getBoundingClientRect() function, inside a new array. In which I would use every first for x and every second for y.
Now do not confuse this with the position within the array, I would like to know how I can "convert" the element from a query so I can use the getBoundingClientRect() function.
I hope this is all the information needed. I myself researched on here, but I could not find anything that was near my (rather big) demand.
I do not have any code, which I think would be useful.
I have found a solution myself. It is definitely not the smoothest nor the fastest solution, but it works.
for(iAllPoints=0;iAllPoints<(aPoints-1);iAllPoints++)
{
//Creating necesarry variables and asking for the needed data from CSS
var sPointPos = document.querySelector(".startPoint").getBoundingClientRect();
var tarPoints = document.querySelector(".target");
var AOfTarPoints = document.getElementsByClassName("target").length;
var calculatedDistances = [];
//Demanding all coordinates from each target point. Aswel as calculating the distance
if (iAllPoints!=(aPoints-2))
{
for(i = 0;i<AOfTarPoints;i++)
{
tarPoints = document.querySelector(".target");
//Calculating
var SideA = sPointPos.top - tarPoints.getBoundingClientRect().top;
var SideB = sPointPos.left - tarPoints.getBoundingClientRect().left;
var CEPDistance = Math.sqrt(Math.pow(SideA,2)+Math.pow(SideB,2));
calculatedDistances[i] = CEPDistance;
tarPoints.classList.add("inCalculation");
tarPoints.classList.remove("target");
}
minimum = Math.min.apply(Math,calculatedDistances);
var smallestDistance = document.querySelector(".inCalculation");
document.querySelector(".startPoint").classList.add("used");
document.querySelector(".startPoint").classList.remove("startPoint");
smallestDistance.classList.add("startPoint");
smallestDistance.classList.remove("inCalculation");
//Reseting the left unused points for next point
document.querySelector(".inCalculation").classList.add("target");
document.querySelector(".inCalculation").classList.remove("inCalculation");
finalDistance += minimum;
}
else
{
for(i = 0;i<AOfTarPoints;i++)
{
tarPoints = document.querySelector(".target");
//Calculating
var SideA = sPointPos.top - tarPoints.getBoundingClientRect().top;
var SideB = sPointPos.left - tarPoints.getBoundingClientRect().left;
var CEPDistance = Math.sqrt(Math.pow(SideA,2)+Math.pow(SideB,2));
calculatedDistances[i] = CEPDistance;
tarPoints.classList.add("inCalculation");
tarPoints.classList.remove("target");
}
minimum = Math.min.apply(Math,calculatedDistances);
var smallestDistance = document.querySelector(".inCalculation");
document.querySelector(".startPoint").classList.add("used");
document.querySelector(".startPoint").classList.remove("startPoint");
smallestDistance.classList.add("used");
smallestDistance.classList.remove("inCalculation");
finalDistance += minimum;
}
I haven't given every single Variable, but you should be able to understand it either way.

appendChild with onclick function that passes through the div's value

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!

Loop reload same trial instead of next one Qualtrics

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_3rCr2DIzW2cv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UUSnUZT,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!

Text based rpg javascript practice project

I was told making a game would be a good way to learn how to use javascript properly so I have started a game in which thus far the player is prompted to create a hero, and then assign attributes to it based on its hero type(magerouge, necromancer, warlock, or shaman) however when I get to the point of assigning attributes it always says the user picked a necromancer no matter what class he actually chose. So in short something is wrong with my function called "defaultAssign". I hope i am posting this question properly, if i am posting incorrectly please let me know so I can try to fix it, this is my first question. Here is my code:
var heroArray = [];
var yourHero ="";
var hero = {
characterType:"",
Damage:0,
Health:0,
Mana:0,
ManaRegenRate:0,
HealthRegenRate:0,
SpecialSkills:[]
};
var mainMenu = function(){
var nameCheck = prompt("What is your Character's Name?").toUpperCase() ;
for( var i = 0;i <= heroArray.length ; i++){
if (nameCheck === heroArray[i]){
alert("We have found your hero change this string later");
runGame(heroArray[i]);
}
else{
alert("You Must Create a Champion");
var heroName = prompt("What Will You Name Your Sorcerer!").toUpperCase;
characterCreator(heroName);
/*use a loop with a regular expression here to check if the name is avalible, if it is countinue, if not
prompt the user for another name
*/
}
/* run "gameSave" for particular hero
Run the main Game function and print to the console:
"Ah yes "+yourHerosNameHere+"," +hisOrHer+" tale echoes far and wide. We last spoke of his journey to"
+insertCurrentCityHere+" where "+heOrShe+" "mostRecentAction"."
*/
}
}
var characterCreator = function(yourHero){
yourHero = Object.create(hero);
yourHero.characterType = prompt("Choose your Character Type:\n"+
"MageRouge\n"+
"Warlock\n"+
"Shaman\n"+
"Necromancer").toUpperCase;
defaultAssign(yourHero.characterType)
}
function defaultAssign(playersType){
for (var j = 0 ; j <= 3 ; j++){
if (playersType === "MAGEROUGE"){
yourHero.Damage=25;
yourHero.Health=50;
yourHero.Mana=15;
yourHero.ManaRegenRate=1;
yourHero.HealthRegenRate=0.4;
yourHero.SpecialSkills=[["pickpocket",],["sneak",],["lockpick",]];
alert("Ahha a powerful Magerouge, choose your skills emphasis wisely,"
+" it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
if(playersType === "WARLOCK"){
yourHero.Damage=50;
yourHero.Health=50;
yourHero.Mana=25;
yourHero.ManaRegenRate=0.6;
yourHero.HealthRegenRate=0.3;
yourHero.SpecialSkills=[["summonDemon",0],["bindDemon",0],["portal",0],["illusion",0]];
alert("Ahha a powerful Warlock, choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
if(playersType === "SHAMAN"){
yourHero.Damage=40;
yourHero.Health=50;
yourHero.Mana=30;
yourHero.ManaRegenRate=0;
yourHero.HealthRegenRate=0.6;
yourHero.SpecialSkills=[["weatherControl",0],["heal",0],["astralProjection",0]]
alert("Ahha a powerful Shaman choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
else if(playersType === "NECROMANCER") {
yourHero.Damage=60;
yourHero.Health=50;
yourHero.Mana=20;
yourHero.ManaRegenRate=0.8;
yourHero.HealthRegenRate=0.4;
yourHero.SpecialSkills=[["raiseDead",0],["petrify",0],["soulSap",0]];
alert("Ahha a powerful Necromancer choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
}
}
/*
create an array of hometowns for the main character to choose from
*/
function skillAssigner(yourHero){
for (var s = 0;s<3;s++){
var p = 0;
while( p < 10 ){
var n = prompt("How many points will you spend on "+yourHero.SpecialSkills[s]+"?");
yourHero.SpecialSkills[s][1] = n;
p +=n;
}
}
}
mainMenu();
Get rid of the else on the line where it checks if the player's type is a Necromancer. It is not necessary.
The for loop is not necessary inside the function defaultAssign (and with its removal, nor are the breaks.)
Finally, toUpperCase is a function so you must invoke it with parentheses, toUpperCase().
Resolving these issues gets your code to work.
You should work on formatting your code (or get an editor that does it for you) to increase its readability-- this will help you find errors.

Trouble with Variable value in function

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.

Categories