Javascript Page Load Total - javascript

I've created a form that is used to calculate monthly expenses. The problem I'm having is on the last page I'm gathering information from previous pages (session to data) that auto fills the fields on the last page. I've created a Javascript that is suppose to subtract the five fields on the page for a grand total but this doesn't work. If I delete the session to data from the load section the Javascript works perfectly.
Page in Question:
http://www.garranteedsolutions.com/budget?chronoform=BudgetPage7
Javascript:
window.addEvent('domready', function() {
$('spendable').addEvent('change', rekenen1);
$('housetotal').addEvent('change', rekenen1);
$('cartotal').addEvent('change', rekenen1);
$('creditortotal').addEvent('change', rekenen1);
$('misctotal').addEvent('change', rekenen1);
});
function rekenen1(){
$('grandtotal').value = Number($('spendable').value) + Number($('housetotal').value) + Number($('cartotal').value) + Number($('creditortotal').value) + Number($('misctotal').value) ;
}
This is the code that I had been using but it requires a change in the form box to perform the action. I've tried this
Javascript:
window.addEvent('domready', function() {
rekenen1;
$('spendable').addEvent(rekenen1);
$('housetotal').addEvent(rekenen1);
$('cartotal').addEvent(rekenen1);
$('creditortotal').addEvent(rekenen1);
$('misctotal').addEvent(rekenen1);
});
function rekenen1(){
$('grandtotal').value =
Number($('spendable').value) + Number($('housetotal').value)
+ Number($('cartotal').value) + Number($('creditortotal').value)
+ Number($('misctotal').value);
}
This is a continuation of me searching for help starting here: http://www.chronoengine.com/forums/viewtopic.php?f=2&t=67427&p=269741#p269741
I don't know Javascript very well and I'm so close to having this form completed. I just can't get the Grand Total to tally up.

The problem is that the events are only firing when you change the values of the form. The form its readonly so they cannot be changed.
Anyway, here is the code optimized:
window.addEvent('domready', function() {
var rekenen1 = function(){
var grandTotal = 0;
$$('#spendable, #housetotal, #cartotal, #creditortotal, #misctotal').each(function(el){
if(el.value.length > 0) grandTotal += el.value.toFloat();
});
$('grandtotal').value = grandTotal;
};
$$('#spendable, #housetotal, #cartotal, #creditortotal, #misctotal').addEvent('onchange', refenen1);
});
That should work. The function checks if the fields have value on them and if they have, they are included in the calculation.
The second code you made fires the error because you are missing a parameter in the addEvent function.
I hope that this can help you :)

This seemed to work! So now I'm trying to figure out how to get commas for the thousands. So if I input 1200 it displays 1,200.
window.addEvent('domready', function() {
$('grandtotal').value = Number($('spendable').value) + Number($('housetotal').value) + Number($('cartotal').value) + Number($('creditortotal').value) + Number($('misctotal').value);
});
Thank you so much for your help!

Related

how to add up the current score, jquery, javascript

I am trying to get a current score to add up every time an answer is correct, what is happening is that I have the questions in a pagination set up and when this answer is correct it give me the score but then when it goes to the next page it refresh the score and if I got that one right it just give me the score for that one again but it doesn't add up.
JS code:
$(function() {
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
var score = 0;
if (correct){
alert('Good job ' + arr2,);
score += 2;
alert (score);
currentScore = score++;
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
});
});
Here is another option - local storage.
Here is a reference W3School Web storage
It's not the most ideal solution, but it can meet your criteria.
let score = localStorage.getItem('score')
score++;
localStorage.setItem('score', score);
Your pages will be able to access the localStorage so you can get the value of score and re-set it.
Hopefully the reference can answer further questions, else leave a comment!
Con: It may not be supported by all browsers.
EDIT:
Here is an example with your code.
$(function() {
let currentScore = localStorage.getItem('score'); // get score
if (currentScore === null){ // if score doesnt exist yet
localStorage.setItem('score', 0); // set score
currentScore = 0; // make currentScore 0
}
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
if (correct){
alert('Good job ' + arr2);
currentScore += 2; //increment current score by 2
alert (currentScore);
localStorage.setItem('score', currentScore); // set the item again with new value
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
});
});
Edit 2:
let currentScore = localStorage.getItem('score'); // get score
currentScore = parseInt(currentScore);
it give me the score but then when it goes to the next page it refresh the score and if I got that one right it just give me the score for that one again but it doesn't add up.
I think your problem is there.
If I understand correctly, when the answer is good, the page refresh and passes to the next question. Your problem is that the score doesn't add up to the previous one.
The score variable is only stored in the current page, like a temporary one. Without saving the score on the server, via ajax or another method, and getting it on the next page, it will not add up. Indeed, score will have a value of 0 due to the refresh.
A simple schema :
score = 0 -> correct answer -> +50 point -> score = 50 -> next page -> score = 0
As you can see, because the javascript you wrote is not assuring the persistance of your information, the previously stored score is lost.
You need to send the score on the server and then get it back when the new page is loaded or to avoid changing page and make your quizz on one and only page, without refreshing.
Keep in mind that everytime you are refresing a page, the javascript is starting again and therefore everything done before is lost.
I hope this was helpful.
Ps: You should place your code in the $( document ).ready(); block just like this :
$( document ).ready(function() {
console.log( "ready!" );
});
It will make your code start when the html DOM (the structure of the html file) is loaded and ready to be manipulated. It can avoid a lot of errors.
Edit2 : What it will look like in your code :
$( document ).ready(function() {
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
var score = 0;
if (correct){
alert('Good job ' + arr2,);
score += 2;
alert (score);
currentScore = score++;
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
});
});
Or, to make this more readable and to avoird having a lot of things in the document.ready block (when you will have a lot of lines/functions) :
$( document ).ready( myNiceFunction() );
var myNiceFunction = function(){
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
var score = 0;
if (correct){
alert('Good job ' + arr2,);
score += 2;
alert (score);
currentScore = score++;
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
}
Ps2 : I know this is not the best website to explain it but I think it is simple enough to make you understand the principle of ajax without losing you into a bunch of technical stuff : here and here
Edit : Grammar and second post-scriptum.
Not sure how you're doing pagination but it should be ajaxed, instead of a full postback, so you don't lose the values on your page.

random numbers on refresh

This is my code for generating random numbers and it works fine when it is triggered by a button in my form.
function random() {
return Math.floor(Math.random() * 100000000);
}
window.onload = function(){
generateRandomNumber();
}
function generateRandomNumber(){
$("#GenerateCode").val(random());
alert('Reference Code: ' + $('#GenerateCode').val());
}
I am using wizard template in my project. What I want to happen is to generate random numbers when I refresh or when the page Loads adn be displayed in a textbox.
Help please....Thank you...
Put this in a script file thats loaded by the page.
$(document).ready(function(){
$('#GenerateCode').val(random());
});
window.onLoad = function () {$('#GenerateCode').val(random())};
A more random number after load
$(function() {
$('#GenerateCode').val(Math.floor(Math.random() * 100000000));
});

display message javascript while a calculation is being made

I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.

Write on html on load

I have created a function who tracks on which slide I am currently on and display the result
e.g. If I am on slide 2 of 3 it will display 2/3
my problem is that right now it is set to do that every time I click the forward arrow but it displays nothing on page load.
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
});
I am trying to find out how to execute this function on page load and where to put it in my code. I am currently learning Javascript through Codecadamedy so I have a basic knowledge of Javascript but I am not enough fluent right now to figure this one out.
Here is a link to the current non working code : http://www.soleilcom.com/metacor_dev/our-plants.php
It looks like you are using jQuery. To execute a function on DOM load in query, do this:
$(document).ready(function() {
/* your code */
});
In your case, that would be:
$(document).ready(function() {
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
});
});
For things like most event handlers, and most other things, initializing at DOM load is good enough. If your code needs to take account for rendered elements or rendered heights, use $(window).load() instead. (In your case DOM load is fine).
Note that this will just establish the click handler at load time. To also run it once, you can do it automatically by either calling the function yourself or triggering a click. To call it yourself, first define another function. The use the function in both the click handler and in one immediate call:
$(document).ready(function() {
var forward = function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
}
$('.forward').click(forward);
forward();
});
Or to trigger it yourself, just define the click handler and trigger a click programatically:
$(document).ready(function() {
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
}).click();
});
It looks like you are using jQuery, so you would use this:
$(document).ready(function(){
// Code here
});
Or, you can use the shortcut:
$(function(){
// Code here
});
Read more about this on the jQuery website
If you give the function a name, then you can use it multiple times:
$(document).ready(function() {
// Bind to click event
$('.forward').click(forwardSlide)
// Execute function on page load
forwardSlide();
});
function forwardSlide() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
};
Is this what you're looking for?

jquery questionnaire

I am trying to create a jquery questionnaire but my little jquery knowledge doesn't help me.
What I have until now is the following http://valogiannis.com/stackoverflow/quest.html
When you click Questions a popup open with two questions.
I want the following: when the user click one of the two answer, the script check his answer. The array CheckFirstAnswer is responsible to "tell" if the first answer is wrong or correct, 0 for wrong, 1 for correct. If user click the correct answer then I want to appear the next question with its answers from the arrays Question,FirstAnswer,SecondAnswer otherwise the corresponding Conclusion proportionately the i value.
I would appreciate any help.
Thanks
[Working demo]
Question manager
// question number
var currentQ = -1;
function showNewQuestion(el) {
currentQ++; // increment question number
$('.messagepop').html( Question[currentQ] + '<br />' +
'<a href="#" class="first">'
+ FirstAnswer[currentQ] + '</a><br />' +
'<a href="#" class="second">'
+ SecondAnswer[currentQ] + '</a><br />' +
'close' );
}
function validate(answer) {
var firstIsTrue = CheckFirstAnswer[currentQ];
// correct answer (new question)
if ( firstIsTrue && answer == 1
|| !firstIsTrue && answer == 2 ) {
showNewQuestion();
}
// incorrect answer (conclusion)
else {
$('.messagepop').html(Conclusion[currentQ]);
}
}
Click handler
$(function () {
$("#container_div").live('click', function (event) {
// which element was clicked
var el = $(event.target);
// first answer was clicked
if (el.hasClass("first")) {
validate(1);
}
// second answer was clicked
else if (el.hasClass("second")) {
validate(2);
}
// questions opener was clicked
else if (el.attr("id") == "questions") {
el.addClass("selected").parent()
.append('<div class="messagepop pop" />');
showNewQuestion();
$(".pop").slideFadeToggle();
}
// popup close was clicked
else if (el.hasClass("close")) {
$(".pop").slideFadeToggle();
$("#questions").removeClass("selected");
}
});
});
You should use $.ajax to send back the answer so that the server can evaluate the answer and send the next question.
Currently, any one with a basic knowledge of JS can see the CheckFirstSnswer array and know the correct answer.
You have an HTML page on the site, hence I don't know the server side programming language you are using.
Make a new page that accepts posts from this page and evaluates the request. This page will send the question id, answer/s selected and auth'ed userid to the new page. The new page will maintain the score at server side and send the next questions

Categories