I am writing an online loan calculator for practice. The data processing is all done on the client-side, however, JSFiddle wants me to use POST. Why is this? Could this be related to the fact that when the calculate button is clicked locally, the form just clears? The code in a JSFiddle: http://jsfiddle.net/TJonS/CuzSM/
Also, why isn't this calculating on click of the button? I have tried debugging multiple times, but Chrome is showing no errors.
Javascript:
function calculate(){
//get the elements
var amount = document.getElementById("amount");
var rate = document.getElementById("rate");
var duration = document.getElementById("duration");
//get the values of the elements
var a = parseFloat(amount.value);
var r = parseFloat(rate.value);
var d = parseFloat(duration.value);
//grab the outputable (readable(ha ha:))) variables
var principal = a;
var interest = r/100/12;
var time = d *12;
//now the calculation variables
var x = Math.pow(1+interest, payments);
var monthlypay = (principal*x*interest)/(x-1);
//if the result is a finite number, then display it. Else we're messed up!
if (isFinite(monthlypay)) {
//fill in outputs
payment.innerHTML = monthlypay.toFixed(2);
total.innerHTML = (monthlypay * payments).toFixed(2);
totalinterest.innerHTML = ((monthlypay*payments)-principal).toFixed(2);
//save the variables
save(amount.value, rate.value,duration.value, a.value, r.value, d.value, principal.value, total.value, totalinterest.value)
}
//else just make the outputs blank as can be.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
}
just put
return false;
at the bottom of your calculate function, to stop the default onClick behavior(of the button) performing a form post.
also...
is your if statement "if (isFinite(monthlypay)) {" actually getting focus?
this seems to be wiping the values every time.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
check your "isFinite(monthlypay)" function is returning true. (most probably never)
Button without post on click:
<input type="button" onclick="dosomething();" value="my button text" />
Related
I'm having issues when trying to access the value of a score that is stored in the localStorage from a variable that is equal to how many questions the user gets right. I thought it would be exactly the same as setting the value but most likely I've done something wrong, and I lack the experience to figure it out..
I Want to display the User's score on the screen's scoreboard where the complete button is. I easily set the score into the localStorage with the setItem(users, score) line, but it seems getItem(score) doesn't work when I want to set displayUser.textContent = getItem(score).
I've tried a lot of different ways, and I always get null. I also noticed every time I submit a new entry to the scoreboard, the key's name keeps the last entries name and stores it on the end.
I'd love to fix this myself, but after making no progress or any leads for 3 hours, I think I might ask for some help. I reused and changed a lot of this code from a class activity in my boot camp so the complete button is just there to remove entries while in development.
Here's all of the relevant JavaScript hopefully
//Variables to Shorten text
var startButton = document.getElementById('startbtn')
var nextButton = document.getElementById('nextbtn')
var finishEarlyButton = document.getElementById('finishEarlyBtn')
var introSection = document.getElementById('intro')
var questionSection = document.getElementById('Question-Section')
var questionElement = document.getElementById('question')
var answerButtons = document.getElementById('Answer-Section')
var scoreboard = document.getElementById('Score-Container')
var userScore = document.getElementById('Score')
var seeScoreBtn = document.getElementById('seeScore')
var restartBtn = document.getElementById('restart')
var finishbtn = document.getElementById('finishbtn')
var userAnswer = ""
var shuffledQuestions, currentQuestionIndex
var score = 0
var userName = document.getElementById('scoreboard-input')
var leaderboard = document.getElementById('leaderboard')
var leaderboardUsers = document.getElementById('leaderboardUsers')
var users = [];
init();
function init() {
var storedUsers = JSON.parse(localStorage.getItem("Users"))
if (storedUsers !== null) {
users = storedUsers;
renderUsers();
}
}
function renderUsers() {
leaderboardUsers.innerHTML = "";
for (var i = 0; i < users.length; i++) {
var user = users[i];
var li = document.createElement("li");
li.textContent = user;
li.setAttribute("data-index", i);
var button = document.createElement("button");
button.textContent = "Complete";
var displayUser = document.createElement("button");
displayUser.textContent = (localStorage.getItem(score));
//displayUser.textContent = "test";
console.log(localStorage.getItem(users.value))
li.appendChild(displayUser);
li.appendChild(button);
leaderboardUsers.appendChild(li);
}
}
function storeUsers() {
//localStorage.setItem("users", JSON.stringify(users));
//localStorage.setItem(JSON.stringify(users), JSON.stringify(score));
localStorage.setItem(users, score);
}
leaderboard.addEventListener("submit", function() {
event.preventDefault();
var userText = userName.value.trim();
var userCorrectAnswers = score.value;
if (userText === "") {
return
}
//users.push(userCorrectAnswers);
users.push(userText);
userName.value = "";
storeUsers()
renderUsers()
console.log
})
leaderboardUsers.addEventListener("click", function(event) {
var element = event.target;
if (element.matches("button") === true) {
var index = element.parentElement.getAttribute("data-index");
users.splice(index, 1);
storeUsers();
renderUsers();
}
})
Let me know if the html or rest of JS is needed!
Well just by looking at the code we can see that you're accessing it via
var storedUsers = JSON.parse(localStorage.getItem("Users"))
and storing it via
localStorage.setItem(users, score);
With the way you're accessing it, you would set it via
localStorage.setItem("Users", JSON.stringify(users));
It is case-sensitive, which is probably why your attempt of using the key users didn't work in your first comment under your storeUsers function.
This is a lot of code to sift through but setting and getting items requires string key-names and stringified values:
localStorage.setItem('users', JSON.stringify(score))
JSON.parse(localStorage.getItem('users'))
This way you should have the same data before and after setting to localStorage.
You are not using localStorage setItem correctly.
localStorage.setItem(users, score);
Both arguments to setItem() must be strings, with the first argument a key, and the second argument the value to store. Your first argument is an array (the data type of your second argument is unclear).
Typical value of a setItem first argument: 'usersScores'.
localStorage.setItem('usersScores', JSON.stringify(score));
Note the use of JSON.stringify() to convert score to a string, because localStorage only stores data in string form.
You are also not using getItem correctly:
localStorage.getItem(score)
getItem must be called with the key used in setItem:
localStorage.getItem('userScores')
And since score was saved as a string, you need to convert it back when you read it from localStorage:
score = JSON.parse(localStorage.getItem('userScores'))
How to use localStorage is explained clearly in MDN web docs Using the Web Storage API.
I have an html form that I want to use javascript to calculate the total based on values of the form selection.
I was able to get my code work, but after trying to save it to JS fiddle it doesn't seem to be calculating anymore. Is there something in my code that is causing the error?
Here is the link to my full code:
https://jsfiddle.net/kmurray13/gc02Lsmh/
Here is just my javascript:
function calculatePrice(){
//Get selected data
var elt = document.getElementById("Quantity");
var quantity = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("size");
var size = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("page_count");
var page_count = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("cover_stock");
var cover_stock = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("text_stock");
var text_stock = elt.options[elt.selectedIndex].value;
//convert data to integers or decimals
quantity = parseInt(quantity);
size = parseFloat(size);
page_count = parseInt(page_count);
cover_stock = parseFloat(cover_stock);
text_stock = parseFloat(text_stock);
//calculate total value
var total = ((cover_stock * quantity)) + ((text_stock * page_count) * quantity);
//print value to PicExtPrice
document.getElementById("PicExtPrice").value=total;
}
My goal is to get the calculation when you click the 'Calculate Price' button, but I am not sure what I have done to the code to cause this error.
No it's not anything in your code that's causing the issue. It's because you were loading the javascript in the onload event thus the calculatePrice function wasn't present in the DOM thus you were getting the error. Fixed here: https://jsfiddle.net/fm3g64x0/
This is because jsFiddle is configured by default to wrap your JS code in onload event handler. If you look in your console you are getting a ReferenceError for calculatePrice() because it is out of scope.
In the Javascript jsFiddle pane, click where it says JavaScript + No-Library (pure JS) and where it says Load Type select No wrap - bottom of and rerun your code.
I am busy with making a kind of invoice system, where the user can make invoices very easily. Now I am at the point where I have to count up, per product, three different variables/items, but instead of counting them up, my javascript code puts it like text (with the + operator).
Example:
selectmenu 1 = option 0 (where VAT = 8.50 euro's)
selectmenu 2 = option 1 (where VAT = 12.76 euro's)
Now the output has to be (8.50+12.76)= 21.26
The output in my situation is = 8.5012.76
My (partial) javascript code:
$("select#product").on("change", function (e) {
var $row = $(e.target).closest('.productitem');
var selVal = $row.find('#product').val();
var totalvat;
var currentVat = $('#totalvat').val();
var NLhoog = 1.21;
var price0EXC = 40.49;
var price0INC = (price0EXC * NLhoog).toFixed(2);
var price0VAT = (price0INC - price0EXC).toFixed(2);
var price1EXC = 60.74;
var price1INC = (price1EXC * NLhoog).toFixed(2);
var price1VAT = (price1INC - price1EXC).toFixed(2);
if (selVal === "0") {
$row.find("input#vat").val(price0VAT);
$row.find("input#priceEXC").val(price0EXC);
$row.find("input#priceINC").val(price0INC);
totalvat = (currentVat + price0VAT);
$('input#totalvat').val(totalvat);
} else if (selVal === "1") {
$row.find("input#vat").val(price1VAT);
$row.find("input#priceEXC").val(price1EXC);
$row.find("input#priceINC").val(price1INC);
totalvat = currentVat+price1VAT;
$('input#totalvat').val(totalvat);
}
});
I have let the unimportant part of the code away.
If you know what I am doing wrong, please let me know :)
Think this may help?
var currentVat = parseFloat($('#totalvat').val());
You are using var currentVat = $('#totalvat').val(); to get the value from an input I assume? This is a string which will need to be parsed at some to a relevant datatype. When + is used with a string the compiler performs concatenation.
Try something like:
var currentVat = parseFloat($('#totalvat').val());
Or do it later on with:
parseFloat(currentVat);
As you're using numbers as currency I'd consider adding the suffix .ToFixed(2) at the end, and maybe some other formatting
Hello I am new to Js and I want to make a cost calculation function. So far it works but Its not what I want to have. Here is how it looks
<script>
function finalCost(){
var roomType = document.getElementById("roomtype").value;
var roomNum = document.getElementById("rooms").value;
var personNum = document.getElementById("atoma").value;
var childNum = document.getElementById("paidia").value;
var resFacilities =
document.getElementById("meal").value;
var atoma = childNum + personNum;
var roomty = (parseInt(roomType));
var total = +roomty + +atoma + +((resFacilities));
document.getElementById("result").innerHTML = total;
}
</script>
However, I want to have something like that: ( It wont work I know)
<script>
function finalCost(){
var roomType = document.getElementById("roomtype").value;
var roomNum = document.getElementById("rooms").value;
var personNum = document.getElementById("atoma").value;
var childNum = document.getElementById("paidia").value;
var resFacilities =
document.getElementById("meal").value;
var atoma = childNum + personNum;
var roomty = (parseInt(roomType));
var total = +roomty*roomNum + +atoma + +((resFacilities)*atoma);
document.getElementById("result").innerHTML = total;
}
</script>
If I enter the above code the cost wont work at all If i enter it without the *roomNum the cost will work without the meal included.
Please give me some advice as I am really frustrated by this issue.
If i understand this correctly because I'm unsure of the exact calculation you are trying to compute:
// Total calculated as room type times number of rooms times number of people.
// Adding meal costs per person.
var total = roomty*roomNum*atoma +(resFacilities*atoma);
Your code is working fine please see console output
Of this is not what you looking for. Put your html, javascript somewhere at one place. Where you code can be executed.
I am trying to output only articles if authorsId = authorId.
Beside that the whole function works exactly as I want, here it is:
The general idea is to limit access to only own articles.
So, my question is: how do I limit the results to show only articles written by the owner of the page we are on (authorsId = authorId).
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
alert(authorsid) // authors of each article - it returns the proper values
alert(authorid) // author of the page we are on - it returns the proper value
var count = 0;
rel.options[x] = new Option(title, id, authorid); // lign that returns results
title = '';
id = '';
authorid = '';
}
}
I suspect the problem is when you try performing a conditional statement (if/then/else) that you are comparing a number to a string (or a string to a number). This is like comparing if (1 == "1" ) for example (note the double quotes is only on one side because the left would be numeric, the right side of the equation would be a string).
I added a test which should force both values to be strings, then compares them. If it still gives you problems, make sure there are no spaces/tabs added to one variable, but missing in the other variable.
Also, I changed your "alert" to output to the console (CTRL+SHIFT+J if you are using firefox). The problem using alert is sometimes remote data is not available when needed but your alert button creates a pause while the data is being read. So... if you use alert, your code works, then you remove alert, your code could reveal new errors (since remote data was not served on time). It may not be an issue now, but could be an issue for you going forward.
Best of luck!
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
console.log("authorsid = "+authorsid); // authors of each article - it returns the proper values
console.log("authorid = "+authorid); // author of the page we are on - it returns the proper value
if( authorsid.toString() == authorid.toString() )
{
rel.options
var count = 0;
console.log( authorsid.toString()+" equals "+authorid.toString() );
rel.options[rel.options.length] = new Option(title, id, authorid); // lign that returns results
}
else
{
console.log( authorsid.toString()+" NOT equals "+authorid.toString() );
}
title = '';
id = '';
authorid = '';
}
Did you check the console for messages? Did it correctly show authorid and authorsid?
I have edited the script and made a couple of additions...
The console will tell you if the conditional check worked or not (meaning you will get a message for each record). See the "if/else" and the extra "console.log" parts I added?
rel.options[x] changed to equal rel.options[rel.options.length]. I am curious on why you set rel.options.length=0 when I would instead have done rel.options=new Array();