Trouble with Variable value in function - javascript

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.

Related

Multiple of document.getElementById("elementId").innerHTML = () causing second one to return as null

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.

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!

After Effects Script - Expression Controller Coordinates

Writing a script for After Effects 2015. Trying to copy coordinate data from a point expression controller to a layer's position data. I can't seem to find a way to point to the Expression Controller values.
for (i = 1; i <= app.project.activeItem.selectedLayers[0].property("Effects").numProperties; i++) {
app.project.items[2].layer(i).property("position").setValue(app.project.activeItem.selectedLayers[0].property("Effects").property(i).value);
}
I've also tried this:
for (i = 1; i <= app.project.activeItem.selectedLayers[0].property("Effects").numProperties; i++) {
app.project.items[2].layer(i).property("position").setValue(app.project.activeItem.selectedLayers[0].property("Effects").property(i).property("Point").value);
}
Any help would be appreciated. I'm hoping I didn't make any typos...
This should get you going. You need a layer with an expression point controler and it needs to be selected. I'm using here the match names of the effects. You can use the names from interface as well. I suggest getting the rd_GimmePropPath script from redefinery.com. Helps me every time.
function main() {
app.beginUndoGroup("XXX");
var curComp = app.project.activeItem; // get the current comp
if (!curComp || !(curComp instanceof CompItem)) {
// doulble check
alert("noComp");
return;
};
var layerwithpointcontroller = curComp.selectedLayers[0]; // the first selected layer
// get the value of the expression controler
var pointvalue = layerwithpointcontroller.property("ADBE Effect Parade")
.property("ADBE Point Control")
.property("ADBE Point Control-0001")
.value;
$.writeln(pointvalue); // take a look at it
var nullobject = curComp.layers.addNull();// add a null
nullobject.position.setValue(pointvalue);// set its position
app.endUndoGroup();
}
main();

Javascript not recognising function

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

Should all javascript be put inside a load() on body event?

Should I put all this inside a load() body event so that it loads after the page has rendered and the DOM objects have been created? (I did find I had to use .innerhtml rather than .value for it to work.) If so how...
(*I know this is rubbish code, but it is better than my last attempt and worse than my next attempt. Once I get some time to comeback to this I will recreate it using a literal constructor with internal functions. I am not looking to take this Javascript any further in functionality. The back-end php I have will handle security and checks)
<script type="text/javascript">
//To get the price of a product applying discount
function getPrice(location,quantity)
{
//Get the product choice
var e = document.getElementById("productList["+location+"]");
var productSelected = e.options[e.selectedIndex].value;
//TODO: Determine discounts based on product choice
switch(productSelected)
{
case '0':
return 0;
case '1':
return 10;
case '2':
return 15;
}
return null;
}
//To update product only
function updateProduct(location)
{
updateRow(location,document.getElementById("quantity["+location+"]").value);
}
//To update only that row
function updateRow(location,quantity)
{
//Check Quantity is a valid Number and also not a float or negative
if (!isNaN(quantity) && parseFloat(quantity) && isFinite(quantity) && (quantity >= 0)) {
quantity = Math.floor(quantity);
} else {
quantity = 0;
};
//Update the quantity input field to whatever quantity is - Investigate later!
document.getElementById("quantity["+location+"]").value = quantity;
//Store old Price for changing total
var oldTotal = document.getElementById("totalPrice").innerHTML;
var oldLinePrice = document.getElementById("linePrice["+location+"]").innerHTML;
//Calculate and Store Prices to adjust the total
var productPrice = getPrice(location,quantity).toFixed(2);
var newLinePrice = (quantity*productPrice).toFixed(2);
//Apply Updates
document.getElementById("unitPrice["+location+"]").innerHTML = productPrice;
document.getElementById("linePrice["+location+"]").innerHTML = newLinePrice;
document.getElementById("totalPrice").innerHTML = (oldTotal-oldLinePrice+parseFloat(newLinePrice)).toFixed(2);
}
</script>
You only need to put any getElement calls, or calls to functions that get elements, in a load function.
Well, you could, but that then could delay some js code from getting started working on parts of your .html coding which get loaded first. It also makes code be indented more than it needs to be, causing a readability issue.

Categories