Why are my variables being alerted back to me as null? - javascript

Why are my variables being alerted back to me as null?
So, I'm trying to pass a string in a variable back to a main page from an external javascript page via alerts.
At first I thought that the javascript wasn't pulling information from the php page properly, then I tried just typing in a variable directly on the javascript page. Both the pulled information and the information that I described on the javascript directly send null.
Now I know for a fact that the varibles name and email are not null, as I literally just defined them.
Here is the code I am having an issue with.
let name = "test";
let email = 11;
let company = document.getElementById($("#Company").value);
let phone = document.getElementById($("#Phone").value);
let city = document.getElementById($("#City").value);
let state = document.getElementById($("#State").value);
let country = document.getElementById($("#Country").value);
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
Here is the full javascript file:
ROICalc3.js
const getErrorMsg2 = lbl =>
`${lbl} must be a valid percent less than or equal to 100.`;
const focusAndSelect = selector => {
const elem = $(selector);
elem.focus();
elem.select();
};
const processEntries = () => {
let ActiveNumberOfMolds = parseFloat($("#activeNumberOfMolds").value);
let PercentOfDownMolds = parseFloat($("#percentOfDownMolds").value);
PercentOfDownMolds = PercentOfDownMolds * .01;
let AverageLaborHours = parseFloat($("#averageLaborHours").value);
let RepairRatePerHour = parseFloat($("#repairRatePerHour").value);
let CostOfCurrentLifter = parseFloat($("#costOfCurrentLifter").value);
let AverageProfitPerPressHour = parseFloat($("#averageProfitPerPressHour").value);
let EstimatedPriceOfAnAcculifter = parseFloat($("#estimatedPriceOfAnAcculifter").value);
let PercentageReductionInLifterFailureUsingAcculignLifters = parseFloat($("#percentageReductionInLifterFailureUsingAcculignLifters").value);
let AverageNumberOfLiftersPerMold = parseFloat($("#averageNumberOfLiftersPerMold").value);
PercentageReductionInLifterFailureUsingAcculignLifters = PercentageReductionInLifterFailureUsingAcculignLifters * .01;
let LifterCostDifference = (EstimatedPriceOfAnAcculifter - CostOfCurrentLifter);
if (isNaN(ActiveNumberOfMolds) || ActiveNumberOfMolds <= 0) {
alert(getErrorMsg("Enter The Active Number Of Molds"));
focusAndSelect("#activeNumberOfMolds");
} else if (isNaN(AverageNumberOfLiftersPerMold) || AverageNumberOfLiftersPerMold <= 0) {
alert(getErrorMsg("Enter the Average Number Of Lifters Per Mold:"));
focusAndSelect("#averageNumberOfLiftersPerMold");
} else if (isNaN(PercentOfDownMolds) || PercentOfDownMolds <= 0) {
alert(getErrorMsg("Enter the Percentage Of Down Molds:"));
focusAndSelect("#percentOfDownMolds");
} else if (isNaN(AverageLaborHours) || AverageLaborHours <= 0) {
alert(getErrorMsg("Enter the Average Labor Hours:"));
focusAndSelect("#averageLaborHours");
} else if (isNaN(RepairRatePerHour) || RepairRatePerHour <= 0) {
alert(getErrorMsg("Enter the repair rate per hour:"));
focusAndSelect("#repairRatePerHour");
} else if (isNaN(AverageProfitPerPressHour) || AverageProfitPerPressHour <= 0) {
alert(getErrorMsg("Enter the average profit per press hour:"));
focusAndSelect("#averageProfitPerPressHour");
} else if (isNaN(CostOfCurrentLifter) || CostOfCurrentLifter <= 0) {
alert(getErrorMsg("Enter the average profit per press hour:"));
focusAndSelect("#costOfCurrentLifter");
} else if (isNaN(EstimatedPriceOfAnAcculifter) || EstimatedPriceOfAnAcculifter <= 0) {
alert(getErrorMsg("Enter the estimated price of an acculifter:"));
focusAndSelect("#estimatedPriceOfAnAcculifter");
} else if (PercentageReductionInLifterFailureUsingAcculignLifters <= 0) {
alert(getErrorMsg("Enter the percentage reduction in lifter failure using accualign lifters:"));
focusAndSelect("#percentageReductionInLifterFailureUsingAcculignLifters");
} else if (PercentOfDownMolds > 1) {
alert(getErrorMsg2("Enter the percentage of down molds:"));
focusAndSelect("#percentOfDownMolds");
} else if (PercentageReductionInLifterFailureUsingAcculignLifters > 1) {
alert(getErrorMsg2("Enter the Percentage Reduction In Lifter Failure Using Accualign Lifters:"));
focusAndSelect("#percentageReductionInLifterFailureUsingAccualignLifters");
} else {
$("#MRRPA").value = (ActiveNumberOfMolds * PercentOfDownMolds);
let mrrpa = parseFloat($("#MRRPA").value);
$("#ANHPL").value = (mrrpa * AverageLaborHours);
let anhpl = parseFloat($("#ANHPL").value);
$("#ALCRFLPM").value = ((anhpl * RepairRatePerHour) + (mrrpa * CostOfCurrentLifter * AverageNumberOfLiftersPerMold));
let alcrflpm = parseFloat($("#ALCRFLPM").value);
$("#PLDDM").value = (AverageProfitPerPressHour * anhpl * .3);
let plddm = parseFloat($("#PLDDM").value);
let eacfl = (plddm + alcrflpm);
$("#EACFL").value = (eacfl);
$("#CDBCLVAL").value = (EstimatedPriceOfAnAcculifter - CostOfCurrentLifter);
let pldtd = (PercentageReductionInLifterFailureUsingAcculignLifters * plddm);
let cdbclval = parseFloat($("#CDBCLVAL").value);
$("#TCDBCLVAL").value = (cdbclval * (ActiveNumberOfMolds * AverageNumberOfLiftersPerMold));
let tcdbclval = parseFloat($("#TCDBCLVAL").value);
let acrnm = ((anhpl * RepairRatePerHour * PercentageReductionInLifterFailureUsingAcculignLifters) + (EstimatedPriceOfAnAcculifter * AverageNumberOfLiftersPerMold * ActiveNumberOfMolds * PercentOfDownMolds * PercentageReductionInLifterFailureUsingAcculignLifters));
let cdnlptrc = (tcdbclval + acrnm + pldtd);
let rlfcical = (eacfl - cdnlptrc);
$("#RLFCICAL").value = rlfcical;
$("#EMUUPI").value = ((tcdbclval / rlfcical) * 12).toFixed(2);;
let emuupi = parseFloat($("#EMUUPI").value);
console.log("EACFL: " + eacfl);
console.log("cdnlptrc: " + cdnlptrc);
document.getElementById("MRRPA").innerHTML = mrrpa + " Molds";
document.getElementById("ANHPL").innerHTML = anhpl + " Hours";
document.getElementById("ALCRFLPM").innerHTML = "$" + alcrflpm;
document.getElementById("PLDDM").innerHTML = "$" + plddm;
document.getElementById("CDBCLVAL").innerHTML = "$" + cdbclval;
document.getElementById("TCDBCLVAL").innerHTML = "$" + tcdbclval;
document.getElementById("RLFCICAL").innerHTML = "$" + rlfcical;
document.getElementById("EACFL").innerHTML = "$" + eacfl;
document.getElementById("EMUUPI").innerHTML = emuupi + " Months";
document.getElementById("ACRNM").innerHTML = "$" + acrnm;
document.getElementById("PLDTD").innerHTML = "$" + pldtd;
document.getElementById("CDNLPTRC").innerHTML = "$" + cdnlptrc;
if (rlfcical > 0) {
document.getElementById("RLFCICAL").style.color = "green";
} else {
document.getElementById("RLFCICAL").style.color = "red";
}
if (eacfl > 0) {
document.getElementById("EACFL").style.color = "red";
} else {
document.getElementById("EACFL").style.color = "green";
}
if (alcrflpm > 0) {
document.getElementById("ALCRFLPM").style.color = "red";
} else {
document.getElementById("ALCRFLPM").style.color = "green";
}
if (plddm > 0) {
document.getElementById("PLDDM").style.color = "red";
} else {
document.getElementById("PLDDM").style.color = "green";
}
if (tcdbclval > 0) {
document.getElementById("TCDBCLVAL").style.color = "red";
} else {
document.getElementById("TCDBCLVAL").style.color = "green";
}
if (cdbclval) {
document.getElementById("CDBCLVAL").style.color = "red";
} else {
document.getElementById("CDBCLVAL").style.color = "green";
}
if (emuupi > 0) {
document.getElementById("EMUUPI").style.color = "green";
} else {
document.getElementById("EMUUPI").style.color = "red";
}
if (anhpl > 0) {
document.getElementById("ANHPL").style.color = "red";
} else {
document.getElementById("ANHPL").style.color = "green";
}
if (mrrpa > 0) {
document.getElementById("MRRPA").style.color = "red";
} else {
document.getElementById("MRRPA").style.color = "green";
}
if (acrnm > 0) {
document.getElementById("ACRNM").style.color = "red";
} else {
document.getElementById("ACRNM").style.color = "green";
}
if (pldtd > 0) {
document.getElementById("PLDTD").style.color = "red";
} else {
document.getElementById("PLDTD").style.color = "green";
}
if (cdnlptrc > 0) {
document.getElementById("CDNLPTRC").style.color = "red";
} else {
document.getElementById("CDNLPTRC").style.color = "green";
}
let name = "test";
let email = 11;
let company = document.getElementById($("#Company").value);
let phone = document.getElementById($("#Phone").value);
let city = document.getElementById($("#City").value);
let state = document.getElementById($("#State").value);
let country = document.getElementById($("#Country").value);
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
let result = document.querySelector('.result');
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "https://staging-dmecompany.kinsta.cloud/Submissions/submitjson.php";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
document.getElementById("result").innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify({
"Name": name,
"Email": email,
"Company": company,
"Phone": phone,
"City": city,
"State": state,
"Country": country,
"ActiveNumberOfMolds": ActiveNumberOfMolds,
"PercentOfDownMolds": PercentOfDownMolds,
"Average Labor Hours": AverageLaborHours,
"RepairRatePerHour": RepairRatePerHour,
"AverageProfitPerPressHour": AverageProfitPerPressHour,
"AverageNumberOfLiftersPerMold": AverageNumberOfLiftersPerMold,
"rlfcical": rlfcical,
"LifterCostDifference": LifterCostDifference,
"anhpl": anhpl,
"alcrflpm": alcrflpm,
"plddm": plddm,
"cdbclval": cdbclval,
"pldtd": pldtd,
"cdbclval": cdbclval,
"emuupi": emuupi,
"mrrpa": mrrpa,
"acrnm": acrnm,
"pldtd": pldtd,
"cdnlptrc": cdnlptrc
});
// Sending data with the request
xhr.send(data);
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#calculate").addEventListener("click", processEntries);
$("#activeNumberOfMolds").focus();
});
Can you tell me why these variables are getting alerted back to me as null?
Edit: #1:
I tried swapping the code to this:
let name = "test";
let email = 11;
let company = document.getElementById("Company").value;
let phone = document.getElementById("Phone").value;
let city = document.getElementById("City").value;
let state = document.getElementById("State").value;
let country = document.getElementById("Country").value;
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
The first alert had, "test"
The second alert had, "11"
All of the rest of the alerts were, "Undefined".
The alerts seem to be feeding back data now if the variables are described in the javascript code itself. I don't seem to be able to pull them from my php file.

.value should not be in the argument to document.getElementById(), it should be used on the result of this.
And you shouldn't call $() or use the # prefix in the argument to getElementById(), the argument should just be the ID by itself.
let company = document.getElementById($("#Company").value);
should be
let company = document.getElementById("Company").value;
Or if $() is an abbreviation for document.querySelector(), you can write
let company = $("#Company").value;
If it's jQuery, then the correct syntax is
let company = $("#Company").val();

Related

Speed typing test

In this JavaScript code they had 17 test cases, all the 17 test cases two test cases are not comming they are
When the reset button is clicked, an HTTP request should be made to get a random quotation from the given URL and the value in the HTML paragraph element with id quoteDisplay should be replaced with quotation received in the response
When page is opened, an HTTP request should be made to get a random quotation from the given URL and the HTML paragraph element with id quoteDisplay should have the quotation received in the response.
Please help me
let timerEl = document.getElementById("timer");
let speedTypingTestEl = document.getElementById("speedTypingTest");
let quoteDisplayEl = document.getElementById("quoteDisplay");
let quoteInputEl = document.getElementById("quoteInput");
let submitBtnEl = document.getElementById("submitBtn");
let resetBtnEl = document.getElementById("resetBtn");
let spinnerEl = document.getElementById("spinner");
let countdown = 0;
function getQuoteDisplay() {
let randomUrl = "https://apis.ccbp.in/random-quote";
let options = {
method: "GET",
};
fetch(randomUrl, options)
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
quoteDisplay(jsonData.content); // use jsonData.content instead
});
}
submitBtn.addEventListener("click", function() {
let intervalId = setInterval(function() {
countdown = countdown + 1;
timerEl.textContent = countdown;
}, 1000);
});
spinnerEl.classList.add("d-none");
for (let result of searchResults) {
createAndAppendSearchResult(result);
}
function searchWikipedia(event) {
if (event.key === "Enter") {
spinnerEl.classList.remove("d-none");
searchResultsEl.textContent = "";
let searchInput = quoteInputEl.value;
let url = "https://apis.ccbp.in/random-quote" + quoteInput;
let options = {
method: "GET"
};
fetch(url, options)
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
let {
search_results
} = jsonData;
displayResults(search_results);
});
}
}
resetBtnEl.addEventListener("click", function() {
getAllValues();
var string_a = jsonData.content;
var string_b = str;
var n = string_a.localeCompare(string_b);
var textVal = document.getElementById('quoteInput').value;
if (n == 1 && textVal == "") {
clearInterval(cancel);
feedback.innerText = "You typed in " + seconds + " seconds";
} else if (n == -1 || textVal == "") {
feedback.innerText = "You typed incorrect sentence";
} else {}
});

AngularJS: Trying to display content using ng-repeat, but page is shown to be blank

Here is the page where I'm trying to display content. It's showing up blank. My application is a single page application, so most of the code is in the index.html file
verbPractice.html
<div>
<h1>Practice verbs here</h1>
<div class="row" ng-repeat="sentence in listOfSentences">
<div class="col-xs-12">
<p>{{sentence.first}} {{sentence.second}} {{sentence.third}}</p>
</div>
</div>
</div>
This page is linked to from another page called verbSelect.html. Here is the relevant code from that page
<div class="btn btn-primary" ui-sref="app.verbPractice" ng-click="storeInfo(); generateSentences()">Submit</div>
Both the above pages are under the same controller called verbController:
(function() {
'use strict';
angular.module('arabicApp')
.controller('verbController', ['$scope', 'verbFactory', 'pronounFactory', 'attachedFactory', function($scope, verbFactory, pronounFactory, attachedFactory){
//Gets verbs from server
$scope.verbArray = verbFactory.getVerbs().query(
function(response) {
$scope.verbArray = response;
}
);
//Gets pronouns from server
$scope.pronouns = pronounFactory.getPronouns().query(
function(response) {
$scope.pronouns = response;
}
);
$scope.attached = attachedFactory.getAttached().query(
function(response) {
$scope.attached = response;
}
);
//Stores the array of selected verbs
$scope.selectedVerbs = [];
$scope.numSelectedVerbs = 0;
//Searches theArray for name and returns its index. If not found, returns -1
$scope.searchArray = function(theArray, name) {
for (var i = 0; i < theArray.length; i++) {
if (theArray[i].name === name) {
return i;
}
}
return -1;
};
//Adds verbs to selected list
$scope.addToSelected = function(theVerb) {
var num = $scope.searchArray($scope.selectedVerbs, theVerb.name);
var divToChange = document.getElementById("verbSelect_"+theVerb.name);
if (num > -1) { //Found. Remeove it from selectedVerbs
$scope.selectedVerbs.splice(num, 1);
divToChange.className = divToChange.className.replace( /(?:^|\s)listItemActive(?!\S)/g , '' );
$scope.numSelectedVerbs = $scope.numSelectedVerbs - 1;
} else { //Not found. Add it in
$scope.selectedVerbs.push(theVerb);
divToChange.className += " listItemActive";
$scope.numSelectedVerbs = $scope.numSelectedVerbs + 1;
}
};
//Stores how many practice questions the user wants
$scope.howMany = 0;
//Stores what tense of verbs the user wants
$scope.verbTense = "Both";
//Stores what form the user wants
$scope.verbVoice = "Both";
//Include commands?
$scope.includeCommands = false;
//Sentense that will be generated
$scope.listOfSentences = [];
$scope.generateSentence = function(isCommand, theTense, theVoice) {
var sent = {"first": "", "second": "", "third": ""};
var attachedPicker = Math.floor(Math.random()*14);
var attachedToUse = $scope.attached[attachedPicker].attached;
var pronounPicker = Math.floor(Math.random()*14);
var pronounToUse = $scope.pronouns[pronounPicker].pronoun;
sent.first = pronounToUse;
var verbPicker = Math.floor(Math.random()*$scope.numSelectedVerbs);
var verbToUse = $scope.selectedVerbs[verbPicker][theTense][pronounToUse];
if (isCommand === true) {
sent.second = verbToUse;
} else {
if (theVoice === "Passive") {
if (theTense === "Past") { sent.second = "were"; }
else { sent.second = "are"; }
sent.third = verbToUse;
} else {
sent.second = verbToUse;
sent.third = attachedToUse;
}
}
return sent;
};
$scope.storeInfo = function() {
localStorage.setItem("howMany", $scope.howMany);
localStorage.setItem("verbTense", $scope.verbTense);
localStorage.setItem("verbVoice", $scope.verbVoice);
localStorage.setItem("includeCommands", $scope.includeCommands);
};
$scope.getStoredInfo = function() {
$scope.howMany = localStorage.getItem("howMany");
$scope.verbTense = localStorage.getItem("verbTense");
$scope.verbVoice = localStorage.getItem("verbVoice");
$scope.includeCommands = localStorage.getItem("includeCommands");
};
//Generates sentences using the variables from verbSelect
$scope.generateSentences = function() {
$scope.getStoredInfo();
var tensePicker;
var voicePicker;
var doCommand;
var rand;
for (var i = 0; i < $scope.howMany; i++) {
//Picks the verb tense
if ($scope.verbTense === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { tensePicker = "Past"; }
else { tensePicker = "Present"; }
} else {
tensePicker = $scope.verbTense;
}
//Picks the verb voice
if ($scope.verbVoice === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { voicePicker = "Active"; }
else { voicePicker = "Passive"; }
} else {
voicePicker = $scope.verbVoice;
}
//If the voice is passive, use past tense
if ($scope.verbVoice === "Passive") { tensePicker = "Past"; }
//Determines if the sentence will be a command sentence or not
if ($scope.includeCommands === true) {
rand = Math.floor(Math.random() * 6);
if (rand === 0) { doCommand = true; }
else { doCommand = false; }
} else {
doCommand = false;
}
var sentence = $scope.generateSentence(doCommand, tensePicker, voicePicker);
$scope.listOfSentences.push(sentence);
}
console.log($scope.listOfSentences);
};
}])
;
})();
The variables: howMany, verbTense, verbVoice, isCommand, are set on this verbSelect.html page using ng-model. Both the verbSelect.html page and verbPractice.html page are under the same controller.
Everything seems to be working fine. At the end of my generateSentences() function, I output $scope.listOfSentences to the log, and it shows up without any problems, the array is being populated just fine. However, in my verbPractice.html page, nothing is showing up except the <h1> heading. For some reason, even though the $scope.listOfSentences array is populated, ng-repeat doesn't seem to be looping. Does anyone have any idea why?
Sorry for the long post
Thanks for taking the time to read and answer this question!

how to break a timer while it's not being used anymore

I have problem with removing a timer while it not being used anymore in javascript ?
let say we have a variable tm for the timer and set it with window.setInterval, while it still running we replace it by a new setInterval, how possible to get rid of the first setInterval ?
example code
var tm = setInterval(function(){
console.log('tm1')
}, 10);
tm = setInterval(function(){
console.log('tm2')
}, 10)
this is the real problem
motion:function(ele,cssStart,cssEnd,duration,tangent, easing,loop, complete){
if(ele==null||typeof cssEnd !== 'string') throw new TypeError();
if(!$hd.isElement(ele) || !$hd(ele).isExists()) throw new TypeError();
var validRules = /(left|top|width|color|height|background-color|margin-left|margin-right|margin-top|margin-botom|border-color|padding-left|padding-right|padding-top|border-bottom-width|border-top-width|border-left-width|border-right-width|border-bottom-color|border-top-color|border-left-color|border-right-color|padding-bottom|border-width|opacity|font-size)\s?(?=:).[^;]*(?=;?)/gim;
// filtering css input
cssEnd = cssEnd.replace(/\s{2,}|\n|\t/gim,'').replace(/\s?(:)\s?/gi,'$1').match(validRules);
cssStart = !cssStart?[]:cssStart.replace(/\s{2,}|\n|\t/gim,'').replace(/\s(:)\s/gi,'$1').match(validRules);
if(!cssEnd) throw new Error('invalid css rules, please refer to the documentation about the valid css rules for animation');
// creating properties
var _cssEnd = [],
_paused = false,
_cssStart = [],
_tm = null,
_step,
_complete = typeof complete ==='function'?complete:null,
_loop = 0,
_easing = typeof easing ==='string'?easing.match(/^easein|easeout|easeinout$/)?easing:'easein':'easein',
_tangent = typeof tangent ==='string'?tangent in hd.classes.motionTangents ? tangent:'linear':'linear';
this.ele = $hd(ele),
this.duration = isNaN(duration)?1:parseFloat(duration),
this.loop = isNaN(loop)?0:parseInt(loop),
this.isPlaying = false;
this.complete = false;
// verifying the css rules of the end point
var verify = function(cssStart, cssEnd){
for (var i = 0; i < cssEnd.length; i++) {
var colorPattern = /#[a-z0-9]+|rgba?\s?\(([0-9]{1,3}\s?,\s?)+((([0-9]+)?(\.)?([0-9]+))+)?\)/gi,
name = cssEnd[i].replace(/^([a-z0-9-]+)\s?(?=:).*/gi,'$1'),
value = cssEnd[i].replace(/^[a-z0-9-]+\s?:(.*)/gi,'$1'),
startIndex = $hd(cssStart).inspectData(name+':',false),
startValue = !startIndex.length?this.ele.getcss(name):cssStart[startIndex].replace(/^[a-z0-9-]+:(.*)/gi,'$1');
if(value=='') continue;
// parsing values
if(name.match(/color/i)){
//if color
// validate the color
if(!value.match(colorPattern)) continue;
if(value.match(/#[a-z0-9]+/ig)){
// if hex then convert to rgb
var rgb = $hd(value).hex2rgb(),
value = !rgb?null:rgb;
if(!value) continue;
}
// verifying cssStart's value
startValue = !startValue.match(colorPattern)?this.ele.getcss(name):startValue;
if(!startValue.match(colorPattern)) continue;
if(startValue.match(/#[a-z0-9]+/ig)){
// if hex then convert to rgb
var rgb = $hd(startValue).hex2rgb(),
startValue = rgb==null?null:rgb;
}
// if browser doesn't support rgba then convert the value to rgb
value = !$hd.supports.rgba && value.match(/rgba/i)?value.replace(/(.*)a\s?(\((\d{1,3},)(\d{1,3},)(\d{1,3})).*/i,'$1$2)'):value;
startValue = !$hd.supports.rgba && startValue.match(/rgba/i)?startValue.replace(/(.*)a\s?(\((\d{1,3},)(\d{1,3},)(\d{1,3})).*/i,'$1$2)'):startValue;
// compare and convert the value of both to object
var colora = value.match(/[0-9]{1,3}/g),
colorb = startValue.match(/[0-9]{1,3}/g);
if(colora.length > colorb.length){
colorb.push(this.ele.getcss('opacity'))
}else if(colorb.length>colora.length){
colora.push(colorb[colorb.length-1])
}
_cssEnd.push({
type:'color',
name:name,
value:{
r:parseInt(colora[0]),
g:parseInt(colora[1]),
b:parseInt(colora[2]),
a:colora[3]?parseFloat(colora[3]):null
}
});
_cssStart.push({
type:'color',
name:name,
value:{
r:parseInt(colorb[0]),
g:parseInt(colorb[1]),
b:parseInt(colorb[2]),
a:colorb[3]?parseFloat(colorb[3]):null
}
});
}else{
value = parseFloat(value),
startValue = parseFloat((isNaN(parseFloat(startValue))?parseFloat(this.ele.getcss(name)):startValue));
if(isNaN(value)) continue;
if(isNaN(startValue)) startValue = 0;
_cssEnd.push({
type:'unit',
name:name,
value:parseFloat(value)
});
_cssStart.push({
type:'unit',
name:name,
value:parseFloat(startValue)
});
}
}
};
verify.apply(this,[cssStart,cssEnd]);
// clearing the arguments
cssStart = complete = cssEnd = duration = tangent = loop = ele = verify = null;
if($hd(_cssEnd).isEmpty()) throw new Error('MotionClass::invalid css rules');// raise error if cssEnd is empty
var _pauseTime = 0;
this.play = function(){
if(this.isPlaying) return;
if(!this.ele.isExists() || !this.ele.visible()) {
this.stop();
return;
}
this.isPlaying = true;
_paused = false;
if( $hd(_cssEnd).inspectData('left',true,true).length||
$hd(_cssEnd).inspectData('top',true, true).length)
this.ele.css('position:absolute');
var st = new Date() - _pauseTime;
_tm = window.setInterval(function(){
if(!this.ele.isExists() || !this.ele.visible()) {
this.stop();
return;
}
var pg, delta,
timePassed = new Date() - st;
pg = timePassed / (this.duration*1000);
if (pg > 1) pg = 1;
if(_easing === 'easeout'){
delta = 1 - hd.classes.motionTangents[_tangent](1 - pg);
}else if(_easing==='easeinout'){
if (pg <= 0.5) {
// the first half of animation will easing in
delta= hd.classes.motionTangents[_tangent](2 * pg) / 2
} else {
// the rest of animation will easing out
delta= (2 - hd.classes.motionTangents[_tangent](2 * (1 - pg))) / 2
}
}else{
delta = hd.classes.motionTangents[_tangent](pg);
}
// the movement
_step.call(this,delta);
if(_paused){
window.clearInterval(_tm);
_tm=null;
_pauseTime = timePassed;
this.isPlaying = false;
return;
}
if (pg == 1) {
_pauseTime =0;
if(_loop>=this.loop){
this.complete = true;
this.stop();
if(_complete)_complete.call(null,this);
}else{
_loop++;
st = new Date(),
timePassed = new Date() - st,
pg = 0;
}
}
}.bind(this),15);
};
_step = function(delta){
var styles = '';
for(var i=0;i<_cssEnd.length;i++){
var name = _cssEnd[i].name,
svalue =_cssStart[i].value,
value = _cssEnd[i].value;
if(_cssEnd[i].type == 'color'){
styles += name+':'+(value.a !=null?'rgba(':'rgb(')
+ Math.max(Math.min(parseInt((delta * (value.r-svalue.r)) + svalue.r, 10), 255), 0) + ','
+ Math.max(Math.min(parseInt((delta * (value.g-svalue.g)) + svalue.g, 10), 255), 0) + ','
+ Math.max(Math.min(parseInt((delta * (value.b-svalue.b)) + svalue.b, 10), 255), 0)
+ (value.a ==null?'':',' + $hd(parseFloat((value.a-svalue.a)*delta+svalue.a)).round(1)) +') !important;';
}else{
styles += name+':'+ $hd(parseFloat((value-svalue)*delta+svalue)).round(2) + (name.match(/opacity/i)?'':'px')+ '!important;';
}
this.ele.css(styles);
}
};
this.stop = function(){
this.isPlaying = false;
window.clearInterval(_tm);
_tm=null;
_loop = 0;
};
this.pause = function(){
_paused = true;
};
}
this how the problems came up;
var color = 'rgba('+($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
'1)';
var bcolor = 'rgb('+($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
')';
var motion = new hd.classes.motion(box,'',('height:'+($(1).randomize(10,50))+
'px;border-color:'+bcolor+
';background-color:'+color+
';left :'+((e.x || e.clientX)-(box.rectangle().width/2))+
';top : '+((e.y || e.clientY)-(box.rectangle().height/2))+
';border-top-width:'+($(1).randomize(0,50))),
2,'circle','easeinout',1, function(e){
status.html('Idle');
});
motion.play();
while variable motion has been referenced with an motion class (animation), how possible to stop the first motion's timer if it being replaced with new motion class(animation)
Really easy! clearInterval(tm). If you call them different names, you will be able to differentiate between them.

getting html input value inside javascript class

i am new to javascript and im making a BMI calculator. im making a class in javascript to produce the calculations. currently users could input their height (in feet and inches) and weight. when i run a method within my class. it keeps saying this.feet = null instead of grabbing the value from the input. my javascript code is below. result() is in my html for the submit button.
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0) {
errors.push("Feet");
}
else {
return this.feet
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("Inches")
}
else {
return this.inches;
};
if(isNaN(this.weight) || this.weight < 0) {
errors.push("Weight");
}
else {
return this.weight
}
};
this.inchesConverter = function() {
this.feet = parseFloat(feet);
this.inches = parseFloat(inches);
return parseInt(this.feet*12+this.inches);
};
this.bmi = function() {
var height = this.inchesConverter();
var validater = this.validateInput();
for(r = 0; r < errors.length; r++){
if(errors.length > 0) {
return errors[r] + " must be a valid positive number.";
}
else {
parseFloat((validateWeight * 703) / (Math.pow(height, 2))).toFixed(1);
}
}
};
};
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
function result() {
document.getElementById("lblBMI").innerHTML(test.bmi());
}
Instead of assigning feet.value to this.feet try assigning feet.getAttribute('value')
If you console.log(feet) does it show the proper DOM element?
There is no need to declare the variables with "this."
function calculator(paraFeet,paraInches,paraWeight) {
var feet = paraFeet.value;
var inches = paraInches.value;
var weight = paraWeight.value;
...
you can now remove "this." from every of these variables inside your function
Every browser has JavaScript console on which you can debug your code.
I have some fun to fix it here or there but also you should try it yourself.
Anyway here it is:
function calculator(weight, feet, inches) {
this.weight = weight;
this.feet = feet;
this.inches = inches;
this.validateInput = function() {
var errors = [];
if (!this.validNumber(this.weight, 1000)) {
errors.push("Invalid weight.");
}
if (!this.validNumber(this.feet, 10)) {
errors.push("Invalid hight in feet.");
}
if (!this.validNumber(this.inches, 11)) {
errors.push("Invalid hight in inches.")
}
return errors;
};
this.validNumber = function(num, max) {
if (num.length > 0 && !isNaN(num)) {
var number = parseInt(num);
return number > 0 && number < max + 1;
}
return false;
}
this.displayErrors = function(errors) {
var html = "";
for (error of errors)
html += error + "<br/>";
return html;
};
this.inchesConverter = function() {
var feet = parseInt(this.feet);
var inches = parseInt(this.inches);
return feet * 12 + inches;
};
this.bmi = function() {
var errors = this.validateInput();
if (errors.length > 0) {
return this.displayErrors(errors);
}
var height = this.inchesConverter();
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
function result() {
var getWeight = document.getElementById('txtWeight').value;
var getFeet = document.getElementById('txtHeightFeet').value;
var getInches = document.getElementById('txtHeightInches').value;
var test = new calculator(getWeight, getFeet, getInches);
document.getElementById("lblBMI").innerHTML = test.bmi();
return false;
}
<span>
<label>Weight</label>
<input id="txtWeight">
</span>
<span>
<label>HeightFeet</label>
<input id="txtHeightFeet">
</span>
<span>
<label>HeightInches</label>
<input id="txtHeightInches">
</span>
<button id='run' onClick="return result();">Calculate</button>
<div id="lblBMI"></div>
Figured out what my issue was. The problem arose from my for loop. Working code is posted below!
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0 || this.feet == "") {
errors.push("feet");
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("inches")
};
if(isNaN(this.weight) || this.weight < 0 || this.weight == "") {
errors.push("weight");
};
return errors;
console.log(errors);
};
this.inchesConverter = function() {
var parseFeet = parseFloat(this.feet);
var parseInches = parseFloat(this.inches);
return parseInt(parseFeet*12+parseInches);
};
this.bmi = function() {
var height = this.inchesConverter();
var errors = this.validateInput();
if(errors.length > 0) {
for(r = 0; r < errors.length; r++){
return "Please enter a correct number for " + errors[r];
};
}
else {
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
};
function result(){
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
document.getElementById("lblBMI").innerHTML = test.bmi();
};

Unreachable code in varien/configurable.js Magento

I was taking a look at the Magento source file to try to understand why I can't move varien/configurable.js whithout throwing an error with another extension, so Google Closure Compiler to shrink it, but it returns an error at line 267:
JSC_UNREACHABLE_CODE: unreachable code at line 267 character 8
if($('product-price-'+this.config.productId)){ ^
In particular these is the slice of code:
getAttributeOptions: function(attributeId){
if(this.config.attributes[attributeId]){
return this.config.attributes[attributeId].options;
}
},
Could someone explain me why it throw out that warning?
This is the whole code:
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* #category Varien
* #package js
* #copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* #license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
if (typeof Product == 'undefined') {
var Product = {};
}
/**************************** CONFIGURABLE PRODUCT **************************/
Product.Config = Class.create();
Product.Config.prototype = {
initialize: function(config){
this.config = config;
this.taxConfig = this.config.taxConfig;
if (config.containerId) {
this.settings = $$('#' + config.containerId + ' ' + '.super-attribute-select');
} else {
this.settings = $$('.super-attribute-select');
}
this.state = new Hash();
this.priceTemplate = new Template(this.config.template);
this.prices = config.prices;
// Set default values from config
if (config.defaultValues) {
this.values = config.defaultValues;
}
// Overwrite defaults by url
var separatorIndex = window.location.href.indexOf('#');
if (separatorIndex != -1) {
var paramsStr = window.location.href.substr(separatorIndex+1);
var urlValues = paramsStr.toQueryParams();
if (!this.values) {
this.values = {};
}
for (var i in urlValues) {
this.values[i] = urlValues[i];
}
}
// Overwrite defaults by inputs values if needed
if (config.inputsInitialized) {
this.values = {};
this.settings.each(function(element) {
if (element.value) {
var attributeId = element.id.replace(/[a-z]*/, '');
this.values[attributeId] = element.value;
}
}.bind(this));
}
// Put events to check select reloads
this.settings.each(function(element){
Event.observe(element, 'change', this.configure.bind(this))
}.bind(this));
// fill state
this.settings.each(function(element){
var attributeId = element.id.replace(/[a-z]*/, '');
if(attributeId && this.config.attributes[attributeId]) {
element.config = this.config.attributes[attributeId];
element.attributeId = attributeId;
this.state[attributeId] = false;
}
}.bind(this))
// Init settings dropdown
var childSettings = [];
for(var i=this.settings.length-1;i>=0;i--){
var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
if (i == 0){
this.fillSelect(this.settings[i])
} else {
this.settings[i].disabled = true;
}
$(this.settings[i]).childSettings = childSettings.clone();
$(this.settings[i]).prevSetting = prevSetting;
$(this.settings[i]).nextSetting = nextSetting;
childSettings.push(this.settings[i]);
}
// Set values to inputs
this.configureForValues();
document.observe("dom:loaded", this.configureForValues.bind(this));
},
configureForValues: function () {
if (this.values) {
this.settings.each(function(element){
var attributeId = element.attributeId;
element.value = (typeof(this.values[attributeId]) == 'undefined')? '' : this.values[attributeId];
this.configureElement(element);
}.bind(this));
}
},
configure: function(event){
var element = Event.element(event);
this.configureElement(element);
},
configureElement : function(element) {
this.reloadOptionLabels(element);
if(element.value){
this.state[element.config.id] = element.value;
if(element.nextSetting){
element.nextSetting.disabled = false;
this.fillSelect(element.nextSetting);
this.resetChildren(element.nextSetting);
}
}
else {
this.resetChildren(element);
}
this.reloadPrice();
},
reloadOptionLabels: function(element){
var selectedPrice;
if(element.options[element.selectedIndex].config && !this.config.stablePrices){
selectedPrice = parseFloat(element.options[element.selectedIndex].config.price)
}
else{
selectedPrice = 0;
}
for(var i=0;i<element.options.length;i++){
if(element.options[i].config){
element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-selectedPrice);
}
}
},
resetChildren : function(element){
if(element.childSettings) {
for(var i=0;i<element.childSettings.length;i++){
element.childSettings[i].selectedIndex = 0;
element.childSettings[i].disabled = true;
if(element.config){
this.state[element.config.id] = false;
}
}
}
},
fillSelect: function(element){
var attributeId = element.id.replace(/[a-z]*/, '');
var options = this.getAttributeOptions(attributeId);
this.clearSelect(element);
element.options[0] = new Option('', '');
element.options[0].innerHTML = this.config.chooseText;
var prevConfig = false;
if(element.prevSetting){
prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
}
if(options) {
var index = 1;
for(var i=0;i<options.length;i++){
var allowedProducts = [];
if(prevConfig) {
for(var j=0;j<options[i].products.length;j++){
if(prevConfig.config.allowedProducts
&& prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1){
allowedProducts.push(options[i].products[j]);
}
}
} else {
allowedProducts = options[i].products.clone();
}
if(allowedProducts.size()>0){
options[i].allowedProducts = allowedProducts;
element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
if (typeof options[i].price != 'undefined') {
element.options[index].setAttribute('price', options[i].price);
}
element.options[index].config = options[i];
index++;
}
}
}
},
getOptionLabel: function(option, price){
var price = parseFloat(price);
if (this.taxConfig.includeTax) {
var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
var excl = price - tax;
var incl = excl*(1+(this.taxConfig.currentTax/100));
} else {
var tax = price * (this.taxConfig.currentTax / 100);
var excl = price;
var incl = excl + tax;
}
if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
price = incl;
} else {
price = excl;
}
var str = option.label;
if(price){
if (this.taxConfig.showBothPrices) {
str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
} else {
str+= ' ' + this.formatPrice(price, true);
}
}
return str;
},
formatPrice: function(price, showSign){
var str = '';
price = parseFloat(price);
if(showSign){
if(price<0){
str+= '-';
price = -price;
}
else{
str+= '+';
}
}
var roundedPrice = (Math.round(price*100)/100).toString();
if (this.prices && this.prices[roundedPrice]) {
str+= this.prices[roundedPrice];
}
else {
str+= this.priceTemplate.evaluate({price:price.toFixed(2)});
}
return str;
},
clearSelect: function(element){
for(var i=element.options.length-1;i>=0;i--){
element.remove(i);
}
},
getAttributeOptions: function(attributeId){
if(this.config.attributes[attributeId]){
return this.config.attributes[attributeId].options;
}
},
reloadPrice: function(){
if (this.config.disablePriceReload) {
return;
}
var price = 0;
var oldPrice = 0;
for(var i=this.settings.length-1;i>=0;i--){
var selected = this.settings[i].options[this.settings[i].selectedIndex];
if(selected.config){
price += parseFloat(selected.config.price);
oldPrice += parseFloat(selected.config.oldPrice);
}
}
optionsPrice.changePrice('config', {'price': price, 'oldPrice': oldPrice});
optionsPrice.reload();
return price;
if($('product-price-'+this.config.productId)){
$('product-price-'+this.config.productId).innerHTML = price;
}
this.reloadOldPrice();
},
reloadOldPrice: function(){
if (this.config.disablePriceReload) {
return;
}
if ($('old-price-'+this.config.productId)) {
var price = parseFloat(this.config.oldPrice);
for(var i=this.settings.length-1;i>=0;i--){
var selected = this.settings[i].options[this.settings[i].selectedIndex];
if(selected.config){
price+= parseFloat(selected.config.price);
}
}
if (price < 0)
price = 0;
price = this.formatPrice(price);
if($('old-price-'+this.config.productId)){
$('old-price-'+this.config.productId).innerHTML = price;
}
}
}
}
Please check the below code in reloadOldPrice function:
return price;
if($('product-price-'+this.config.productId)){
$('product-price-'+this.config.productId).innerHTML = price;
}
this.reloadOldPrice();
when you are using return price; the return statement doesn't allow next code to run. So its unreachable, hence garbage.
Either use some condition if you want the function to stop there in specific situations or put that return statement at the end of function or simply remove return price; if its not required.

Categories