Getting an NaN error - Javascript - javascript

Im getting an NaN error in the total grade. Can someone help me to find the cause of this error? Or give me some ideas how to fix this? Im just new to javascript and web development. Sorry for the logic of my code..
here's my code.
function Calculate(){
var term = $("#term").val();
var fac_code = $("#faculty_code").val();
$.ajax({
type: 'POST',
url: 'getrecords.php',
data: {
"done": 1,
"term": term,
"fac_code": fac_code
},
dataType: 'json',
success: function(data)
{
var major = data[3];
var quizzes = data[4];
var homework = data[5];
var attendance = data[6];
var laboratory = data[7];
var activity = data[8];
var recitation = data[9];
var q = +(document.getElementById('quiz').textContent);
var a = +(document.getElementById('atten').textContent);
var h = +(document.getElementById('home').textContent);
var r = +(document.getElementById('reci').textContent);
var m = +(document.getElementById('me').textContent);
var ac = +(document.getElementById('activityy').textContent);
var l = +(document.getElementById('laboratory').textContent);
var ma = $('.me');
var qui = $('.quize');
var homesea = $('.hos');
var re = $('.recits');
var laborat = $('.labo');
var activit = $('.activity');
var attenda = $('.atte');
var MisVisible = ma.is(':visible');
var QisVisible = qui.is(':visible');
var HisVisible = homesea.is(':visible');
var RisVisible = re.is(':visible');
var LisVisible = laborat.is(':visible');
var AisVisible = activit.is(':visible');
var ATisVisible = attenda.is(':visible');
var mt;
var qt;
var ht;
var rt;
var act;
var lt;
var att;
if (MisVisible === true) {
mt = m / 100 * 50 + 50;
}
if (QisVisible === true){
qt = q / 100 * 50 + 50;
}
if(HisVisible === true){
ht = h / 100 * 50 + 50;
}
if(RisVisible === true){
rt = r / 100 * 50 + 50;
}
if(LisVisible === true){
lt = l / 100 * 50 + 50;
}
if(AisVisible === true){
act = ac / 100 * 50 + 50;
}
if(ATisVisible === true){
att = a / 100 * 50 + 50;
}
mtt = mt * (major * 0.01);
qtt = qt * (quizzes * 0.01);
attt = att * (attendance * 0.01);
htt = ht * (homework * 0.01);
rtt = rt * (recitation * 0.01);
actt = act * (activity * 0.01);
ltt = lt * (laboratory * 0.01);
var grade = mtt + qtt + attt + htt + rtt + actt + ltt;
document.getElementById('td_grade').innerHTML = grade;
}
});
}

The best answer would be to know how to use the Dev Tools source pane. Put breakpoints in your code, and start stepping through the code to see the values.
If I were to take a wild guess, one of these is undefined or missing.
var major = data[3];
var quizzes = data[4];
var homework = data[5];
var attendance = data[6];
var laboratory = data[7];
var activity = data[8];
var recitation = data[9];
Or one of these can't be parsed correctly by the unary + as a number
var q = +(document.getElementById('quiz').textContent);
var a = +(document.getElementById('atten').textContent);
var h = +(document.getElementById('home').textContent);
var r = +(document.getElementById('reci').textContent);
var m = +(document.getElementById('me').textContent);
var ac = +(document.getElementById('activityy').textContent);
var l = +(document.getElementById('laboratory').textContent);

Use Chrome's Dev tool by pressing F12 and go to console tab, to check for any variable you can use:
console.log(variable_name);
Additionally, your HTML value maybe not in a form of int so you should not use unary plus to get the value, use this instead to check whether your value is good:
if (!isNaN(parseFloat("10000")){
//do something
}

Related

If..else condition error

I am trying to figure out what is wrong with this following code. The code searches for value in a table and assigns mxCost. The IF..ELSE condition works for all values except 1 and is also reading the table. The IF condition makes the page crash and i am not able to figure out why? Can someone please help me figure out what i am doing wrong here. Any help will be appreciated. Thank you.
$jq("#airTableValues tbody tr").each(function() {
var monthName = months[parseInt(dateSplit[1])-1]+" "+dateSplit[0];
if(monthName==$jq(this).find("td:eq(0)").text().trim())
{
mxCost = $jq(this).find("td:eq(6)").text().trim();
}
});
if (mxCost)
mxCost = (mxCost.substring(1, mxCost.length));
else {
mxCost = 0;
}
var MxStat = document.getElementById("MxStat").value;
MxStat = MxStat/100;
var InflationRate1 = document.getElementById("InflationRate1").value;
InflationRate1 = InflationRate1/100;
var rate3 = document.getElementById("rate3").value;
rate3 = Math.pow(1+rate3/100,1/365)-1;
var mxAdj;
if (MxStat == 1){
mxAdj = mxCost;
} // <------- NOT WORKING!
else if (MxStat != 1) {
var TotalCost = mxCost * 2;
mxAdj = (TotalCost * MxStat) - mxCost;
}
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
var ReturnCalc = ReturnVal * 1000000;
var ReturnPV = Math.floor(ReturnCalc/Math.pow(1+rate3,periods));
document.getElementById("ReturnCondition").value =
(ReturnPV/1000000).toFixed(2);
ReturnCondition = ReturnVal.toFixed(2);
This worked for me
if (MxStat != 1){
var mxAdj = (TotalCost * MxStat) - mxCost;
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
aReturnCondition = ReturnVal.toFixed(2);
}
if (MxStat == 1){
var mxAdj = mxCost;
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
aReturnCondition = parseFloat(ReturnVal).toFixed(2);}

Undefined global variables in function

I'm trying to use javascript to perform calculations on a button click because I don't want the page to refresh when this button is clicked. I wrote a script below:
var name = document.getElementById('recipeName').value;
var lvl = document.getElementById('recipeLvl').value;
var e = document.getElementById("qualitySelect");
var quality = e.options[e.selectedIndex].value;
e = document.getElementById("classSelect");
var craft = e.options[e.selectedIndex].value;
var mat1 = document.getElementById('material1Name').value;
var mat1Qty = document.getElementById('material1Qty').value;
var mat1NQ = document.getElementById('material1NQ').value;
var mat1NQprice = document.getElementById('material1NQprice').value;
var mat1HQ = document.getElementById('material1HQ').value;
var mat1HQprice = document.getElementById('material1HQprice').value;
var mat2 = document.getElementById('material2Name').value;
var mat2Qty = document.getElementById('material2Qty').value;
var mat2NQ = document.getElementById('material2NQ').value;
var mat2NQprice = document.getElementById('material2NQprice').value;
var mat2HQ = document.getElementById('material2HQ').value;
var mat2HQprice = document.getElementById('material2HQprice').value;
var mat3 = document.getElementById('material3Name').value;
var mat3Qty = document.getElementById('material3Qty').value;
var mat3NQ = document.getElementById('material3NQ').value;
var mat3NQprice = document.getElementById('material3NQprice').value;
var mat3HQ = document.getElementById('material3HQ').value;
var mat3HQprice = document.getElementById('material3HQprice').value;
var mat4 = document.getElementById('material4Name').value;
var mat4Qty = document.getElementById('material4Qty').value;
var mat4NQ = document.getElementById('material4NQ').value;
var mat4NQprice = document.getElementById('material4NQprice').value;
var mat4HQ = document.getElementById('material4HQ').value;
var mat4HQprice = document.getElementById('material4HQprice').value;
var mat5 = document.getElementById('material5Name').value;
var mat5Qty = document.getElementById('material5Qty').value;
var mat5NQ = document.getElementById('material5NQ').value;
var mat5NQprice = document.getElementById('material5NQprice').value;
var mat5HQ = document.getElementById('material5HQ').value;
var mat5HQprice = document.getElementById('material5HQprice').value;
var mat6 = document.getElementById('material6Name').value;
var mat6Qty = document.getElementById('material6Qty').value;
var mat6NQ = document.getElementById('material6NQ').value;
var mat6NQprice = document.getElementById('material6NQprice').value;
var mat6HQ = document.getElementById('material6HQ').value;
var mat6HQprice = document.getElementById('material6HQprice').value;
e = document.getElementById("catalyst1");
var crystal1 = e.options[e.selectedIndex].value;
e = document.getElementById('element1');
var element1 = e.options[e.selectedIndex].value;
var crystal1Qty = document.getElementById('crystalQty1').value;
var crystal1Price = document.getElementById('crystalPrice1').value;
e = document.getElementById("catalyst2");
var crystal2 = e.options[e.selectedIndex].value;
e = document.getElementById('element2');
var element2 = e.options[e.selectedIndex].value;
var crystal2Qty = document.getElementById('crystalQty2').value;
var crystal2Price = document.getElementById('crystalPrice2').value;
var notes = document.getElementById('notes').value;
var marketPrice = document.getElementById('marketPrice').value;
function calculate() {
var mat1Cost = (mat1NQ * mat1NQprice) + (mat1HQ * mat1HQprice);
var mat2Cost = (mat2NQ * mat2NQprice) + (mat2HQ * mat2HQprice);
var mat3Cost = (mat3NQ * mat3NQprice) + (mat3HQ * mat3HQprice);
var mat4Cost = (mat4NQ * mat4NQprice) + (mat4HQ * mat4HQprice);
var mat5Cost = (mat5NQ * mat5NQprice) + (mat5HQ * mat5HQprice);
var mat6Cost = (mat6NQ * mat6NQprice) + (mat6HQ * mat6HQprice);
var crystal1Cost = (crystal1Qty * crystal1Price);
var crystal2Cost = (crystal2Qty * crystal2Price);
var total = mat1Cost +
mat1Cost +
mat1Cost +
mat1Cost +
mat1Cost +
mat1Cost +
crystal1Cost +
crystal2Cost;
document.getElementById('totalCost').value = mat1Cost;
return false;
}
I'm new to javascript, and thought declaring the variables right after would make them accessible to any function that I would need to use them in, but they are undefined in the calculate function. If I declare them in calculate() it's fine, so is this a scope problem?
Thanks in advance for any help!
The problem is you're grabbing the elements values before you've assigned anything to them. You're getting a copy, not a reference.
var initialValue = document.getElementById('text').value;
function clickHandler() {
// Notice how I have to grab the value again when I want an updated value
var updatedValue = document.getElementById('text').value;
console.log('Initial:', initialValue);
console.log('Updated:', updatedValue);
}
<input id="text" />
<button onclick="clickHandler()">Click Me</button>
#epascarello has commented the real answer, there is no much science there, this is javascript, therefore is a script language, so as soon as this file is loaded, those variables are filled with the initial data of each field, so, if you want to get the value at the point you press calculate(), you should get your variables.

Why isn't my JavaScriptcode working with prompt and innerHTML?

Im trying to make an online Role Playing Game, but my code is not working. It asks the user what they want their character to be named, and what race they want to be. It would then randomly choose some stats for them, and -- depending upon their race -- add and subtract from their stats.
var nameAndRaceFunction = function(){
var namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
var race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
}
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function(){
if(racePrompt === "elf"){
elfStats();
}else if(racePrompt === "dwarf"){
dwarfStats();
}else if(racePrompt === "man"){
manStats();
}else{
}
}
var elfStats = function(){
var elfStr = str;
var elfInt = int + 1;
var elfHlth = (hlth - 1)*10;
var elfDext = dext + 1;
document.getElementById("strength").innerHTML = elfStr;
document.getElementById("intelligence").innerHTML = elfInt;
document.getElementById("health").innerHTML = elfHlth;
document.getElementById("dexterity").innerHTML = elfDext;
}
var manStats = function(){
var manStr = str + 2;
var manInt = int;
var manHlth = (hlth - 1) * 10;
var manDext = dext;
document.getElementById("strength").innerHTML = manStr;
document.getElementById("intelligence").innerHTML = manInt;
document.getElementById("health").innerHTML = manHlth;
document.getElementById("dexterity").innerHTML = manDext;
}
var dwarfStats = function(){
var dwarfStr = str + 1;
var dwarfInt = int;
var dwarfHlth = (hlth + 1) * 10;
var dwarfDext = dext - 1;
document.getElementById("strength").innerHTML = dwarfStr;
document.getElementById("intelligence").innerHTML = dwarfInt;
document.getElementById("health").innerHTML = dwarfHlth;
document.getElementById("dexterity").innerHTML = dwarfDext;
}
racePrompt is defined inside the nameAndRaceFunction() function scope. It is not accessible outside of it. Further: you lower case it, so later I will check only for race not racePrompt.
One solution would be to make race global like str, int, hlth, dext
var nameAndRaceFunction = function() {
namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
getStatFunction()
}
var namePrompt, race;
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function() {
if (race === "elf") {
elfStats();
} else if (race === "dwarf") {
dwarfStats();
} else if (race === "man") {
manStats();
} else {
}
}
getStatFunction should be called with the race as argument or you should define the variable racePrompt outsite the function
Also, if you mean to make a player, a good idea should be have it as an object and use the nameAndRaceFunction like a constructor

Google Maps Store Locator Display distance in Panel

I am using this version of the store locator https://github.com/googlemaps/js-store-locator
I would like to display the distance to each location once the user has submitted their search input (Enter a location). https://googlemaps.github.io/js-store-locator/examples/panel.html
I tried creating a duplicate of storeLocator.Store.prototype.distanceTo on line 441 of http://pastebin.com/ZGrWN6ib
storeLocator.Store.prototype.distanceTo = function(a) {
var b = this.getLocation(),
c = storeLocator.toRad_(b.lat()),
d = storeLocator.toRad_(b.lng()),
b = storeLocator.toRad_(a.lat()),
e = storeLocator.toRad_(a.lng());
a = b - c;
d = e - d;
c = Math.sin(a / 2) * Math.sin(a / 2) + Math.cos(c) * Math.cos(b) * Math.sin(d / 2) * Math.sin(d / 2);
return 12742 * Math.atan2(Math.sqrt(c), Math.sqrt(1 - c))
};
I am able to pass the first parameter but the second parameter var b = this.getLocation() keeps coming up as undefined
Can I check to see to see if the user location is set, and if so run the function? or do i need to hook into one of the listeners?
if(!this.getLocation()){
return 0;
}
else {
var b = this.getLocation(),
c = storeLocator.toRad_(b.lat()),
d = storeLocator.toRad_(b.lng()),
b = storeLocator.toRad_(a.lat()),
e = storeLocator.toRad_(a.lng());
a = b - c;
d = e - d;
c = Math.sin(a / 2) * Math.sin(a / 2) + Math.cos(c) * Math.cos(b) * Math.sin(d / 2) * Math.sin(d / 2);
return 12742 * Math.atan2(Math.sqrt(c), Math.sqrt(1 - c));
}
You are using this.getLocation(), that means your file has to be a storeLocator.Store.prototype.
The getLocation() method probably belongs to the store-locator.min.js, which should be included in your html file, maybe thats why you can not find the getLocation() method.
In the Google Maps GitHub example page, the store-locator.min.js is included in the panel.html file.
From this example folder, you can see the structure of files.
Got it! So if you want to display the distance in the store list view here's what you can do:
First beautify the store-locator.min.js file for easier reading with something like http://jsbeautifier.org/
Then modify this portion of function storeLocator.Panel.prototype.init_
if (b.geometry) {
this.directionsFrom_ = b.geometry.location;
a.directionsVisible_ && a.renderDirections_();
var c = a.get("view");
c.highlight(null);
var d = c.getMap();
b.geometry.viewport ? d.fitBounds(b.geometry.viewport) : (d.setCenter(b.geometry.location), d.setZoom(12));
c.refreshView();
a.listenForStoresUpdate_();
// New Addition
// You will need to create helper functions to set the cookie, i will include below
storeLocator.setCookie("searchAddy",b.geometry.location,1);
// End New Addition
} else a.searchPosition(b.name)
Then add this function right above storeLocator.Panel.prototype.stores_changed
storeLocator.Panel.prototype.ifDistanceFrom = function(b) {
var str = storeLocator.getCookie('searchAddy');
var regex = /\((-?[0-9]+\.[0-9]+), (-?[0-9]+\.[0-9]+)\)/g;
var latlonArray = [];
var match = regex.exec(str);
while (match) {
latlonArray.push({
"lat" : match[1],
"lon" : match[2]
});
match = regex.exec(str);
};
var a = new google.maps.LatLng(latlonArray[0].lat,latlonArray[0].lon),
b = b.getLocation(),
c = storeLocator.toRad_(b.lat()),
d = storeLocator.toRad_(b.lng()),
b = storeLocator.toRad_(a.lat()),
e = storeLocator.toRad_(a.lng());
a = b - c;
d = e - d;
c = Math.sin(a / 2) * Math.sin(a / 2) + Math.cos(c) * Math.cos(b) * Math.sin(d / 2) * Math.sin(d / 2);
return 12742 * Math.atan2(Math.sqrt(c), Math.sqrt(1 - c));
};
Now modify this portion of function storeLocator.Panel.prototype.stores_changed
for (var b = function() {
a.highlight(this.store, !0)
}, e = 0, f = Math.min(10, c.length); e < f; e++) {
var g = c[e].getInfoPanelItem();
g.store = c[e];
// New Addition
if(storeLocator.checkCookie() != null) {
var distance = this.ifDistanceFrom(g.store);
$(g).find('input').val(distance.toFixed(1));
}
else {
$(g).find('.dist-span').hide();
}
// End New Addition
d && c[e].getId() == d.getId() && $(g).addClass("highlighted");
g.clickHandler_ || (g.clickHandler_ = google.maps.event.addDomListener(g, "click", b));
this.storeList_.append(g)
}
Lastly modify your Data Feed file DataSource.prototype.parse_ function
DataSource.prototype.parse_ = function(csv) {
var stores = [];
var rows = csv.split('\n');
var headings = this.parseRow_(rows[0]);
for (var i = 1, row; row = rows[i]; i++) {
row = this.toObject_(headings, this.parseRow_(row));
var features = new storeLocator.FeatureSet;
// If you have features
features.add(this.FEATURES_.getById('featureName1-' + featureName1));
// New Addition
var distInput = "<span class='dist-span'>Distance: <input class='dist-input' value='' size='2' type='text' /> mi.</span>"
// End New Addition
var position = new google.maps.LatLng(row.Ycoord, row.Xcoord);
var shop = this.join_([row.Street_add], ', ');
var locality = row.Locality+', '+row.State+' '+row.Postcode;
var store = new storeLocator.Store(row.Fcilty_typ, position, features, {
title: row.Fcilty_nam,
// New Addition
address: this.join_([shop, locality, distInput], '<br>'),
// End New Addition
hours: row.Hrs_of_bus
});
stores.push(store);
}
return stores;
};
Below are the helper functions you will need to add to store-locator.min.js for setting the cookie.
storeLocator.setCookie = function(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
// alert('Cookie set: '+ cvalue);
};
storeLocator.getCookie = function (cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
};
return "";
};
storeLocator.checkCookie = function () {
var a = storeLocator.getCookie("searchAddy");
if (a != "") {
return 1;
}
else {
return null;
}
};
Inside the DataSource.prototype.parse_ function I added a new div element within the misc parameter, and used the store id as a unique div class.
var id = row.name.toLowerCase().replace(/[\. ,:-]+/g, '-');
var position = new google.maps.LatLng(row.latitude, row.longitude);
var locality = this.join_([row.state, row.postal_code], ', ');
var store = new storeLocator.Store(id, position, features, {
title: row.name,
address: this.join_([row.street, locality], '<br>'),
phone: row.phone_number,
misc: '<div class="distance '+id+'"></div>',
});
And then inside the DataSource.prototype.toObject_ I just added some jQuery for updating the text when a location is searched.
var panelDiv = document.getElementById('panel');
var panel = new storeLocator.Panel(panelDiv, {
view: view
});
google.maps.event.addListener(panel, 'geocode', function(result) {
panel.stores.forEach(function(store){
var distance = Math.round(store.distanceTo(result.geometry.location));
jQuery('.distance').each(function(){
if (jQuery(this).hasClass(store.getId())) {
jQuery(this).text(distance);
}
});
});
});
There's probably a better way, but this worked in my case.

whats selution code for draw poll bar?

this my code in java script :
function DrawPollBars(BarVar, BarWidth) {
var newbar = new Array();
newbar = BarVar;
var newWidth = new Array();
newWidth = BarWidth;
var IncVa;
TotalVotes = sum(BarVar, BarWidth);
IncVal = parseFloat(TotalVotes / 10);
//var percent = 0.00; var count = 0;
var NewBarWidthb = new Array();
var BarNextVar = new Array();
//NewBarWidth = "NewBarWidth" + x;
NewBarWidthb[x] = 0;
//NewBarWidthb[x] = NewBarWidth;
for (var x = 1; x < BarWidth.length; x++) {
var PollBar = document.getElementById('PollBar' + x);
var PollRate = document.getElementById('PollRate' + x);
if (parseInt(parseInt(BarVar[x]) * 200 / TotalVotes) > 0) NewBarWidthb[x] = parseInt(BarVar[x]) * 200 / TotalVotes;
else if (BarVar[x] >= 0) NewBarWidthb[x] = 1;
else NewBarWidthb[x] = 0;
var pollbar = PollBar.style.width = NewBarWidthb[x] + 'px';
var pollrate = PollRate.innerHTML = parseFloat(BarVar[x]).toFixed(0) + " (" + parseFloat(parseFloat(BarVar[x]) / TotalVotes * 100).toFixed(1) + "%)";
//percent = parseFloat(parseFloat(BarWidth[x]) / TotalVotes * 100).toFixed(2) ;
// count = parseFloat(BarWidth[x]).toFixed(0);
if (BarVar != BarWidth) {
if (parseFloat(BarVar[x]) + IncVal <= parseInt(BarWidth[x])) BarNextVar[x] = parseFloat(BarVar[x]) + IncVal; else BarNextVar = BarWidth;
}
}
var ff = window.setTimeout("DrawPollBars([" + BarNextVar + "],[" + BarWidth + "]);", 90);
}
when click btn for first time it is work ok but in second it seems not correctly
i dont know causes
try to use window.clearTimeout(timeoutID); after you complete the action.
For more details you can read here https://developer.mozilla.org/ro/docs/Web/API/window.setTimeout

Categories