guys. I am trying to create a web-based calculator with basic operations using jQuery. I already have implemented the addition operation. Now, I am hooked in subtraction.
Here is a code snippet when you click on the minus button:
$("#btnSub").click(function () {
holdValue = $("#result").val();
currentValue = $("#result").val("0");
flagSub = "1";
flagNotEmpty = "0";
flagDecimal = "0";
});
Here is a code snippet when you click the equals button:
$("#btnEquals").click(function () {
if (flagNotEmpty == "0") {
alert("Missing Value.");
} else {
if (flagAdd == "1") {
currentValue = $("#result").val();
var output = parseFloat(holdValue) + parseFloat(currentValue);
$("#result").val(parseFloat(output));
} else if (flagSub == "1") {
currentValue = $("#result").val();
var output2 = parseFloat(holdValue) - parseFloat(currentValue);
$("#result").val(parseFloat(output2));
}
}
flagSub = "0";
flagAdd = "0";
flagNotEmpty = "0";
flagDecimal = "0";
});
Variables functions:
flagSub: used to determine that the operation choosen is subtraction
flagNotEmpty: used to determine if a number is pressed after selecting an operator. Displays error message if equal sign is clicked on right after the operator button.
flagDecimal: used to tell the program that a decimal has already been entered. Display error message for decimal point duplication.
Problem with this program is that it cannot perform subtraction when it is the first operation you do. That is, when the browser loads the UI and you do subtraction, nothing happens. BUT, when you do, for example, click 1 + 2 = then the program displays 3 in the textbox. Without refreshing the page, click - 10 =. Difference is displayed.
To start from the beginning, please refresh the page; will just add the CLEAR button after I am done with all the operations.
Just want to know what is wrong with my algorithm. For the complete code with html and css, here is its fiddle.
By the way, I have just started learning jQuery so please forgive me for the kind of messy and might be inefficient way of coding. Help is really much appreciated. Thanks in advance.
flagAdd needs to be initialized, you can alter the btnSub handler to do that
$("#btnSub").click(function () {
holdValue = $("#result").val();
currentValue = $("#result").val("0");
flagAdd = "0";
flagSub = "1";
flagNotEmpty = "0";
flagDecimal = "0";
});
alternatively you could initialize it in the document ready handler Fiddle
Related
I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>
I'm trying to work through an assignment to further my understanding of js but I'm running into some issues that are keeping me from final code. The code executes a short quiz- inputs from radio buttons are taken in and matched to an object containing answers, then outputting a final score.
code at http://jsfiddle.net/8ax9A/3/
issues I'm aware of now :
my $response variable doesn't seem to work.
var $response = $('[name=rad]:checked').val();
counter is listening for clicks through questions. After the last question, I want to report final score. I can't get counter to reach the end of questions + 1, and I cant get an accurate final score listener reported (var finalScore).
if ($response == parseInt(questions[counter].answer, 10)) {
finalScore++;
}
Those are just snippets so check out the fiddle for full code. I'd love some suggestions on how to understand where I'm going wrong.
Here is one way you could do it:
//Initialization
var counter=0;
var score=0;
loadQuestion();
$('#next').on('click',answer);
//functions
function answer(){
// if the user did not answer
if ($('input:radio:checked').length == 0){
alert('You have to answer!');
return;
}
var currentQ=questions[counter];
// if answer is correct
if($('[name=rad]:checked').val()==currentQ.answer){score++;}
counter++;
// if there are no questions left
if(counter >= questions.length) {displayResults(); return;}
loadQuestion();
}
function loadQuestion(){
// clear the radio buttons
$("input:checked").removeAttr("checked");
var currentQ=questions[counter];
// display the question
$('h1').text(currentQ.question);
$('#a1').text(currentQ.choices[0]);
$('#a2').text(currentQ.choices[1]);
$('#a3').text(currentQ.choices[2]);
}
function displayResults(){
$("h1").text("You've finished with a score of " + score + "!");
$('[name=rad], #a1, #a2, #a3, #next').remove();
}
JS Fiddle
I'm just getting into javascript and so far enjoying the logic behind it but i have an issue with Firefox. basicly im generating my javascript from within a php function and its a NON SECURE pin code auth script.
So my php creates a call that passes variables pin number included, when called a modal popup with pinpad opens and the user inputs 4 digits, the pinpad onclick function adds the digits into a password field and after 4 clicks it compares it to a hidden field on the pinpad form, if it matches it calls another generated function to complete the success action, if no match pinpad frame turns red and a bypass button is enabled or they can try again.
This all works fine in Chrome, Opera and even IE but in Firefox it calls the success function after 4 digits even if they don't match the pin field.
Why could this be? Below is the function, but please remember I'm new so it could possibly be better written.
function add(text) {
var TheTextBox = document.pinform.elements['pin'];
var pincheckbox = document.pinform.elements['pincheck'];
var sidbox = document.pinform.elements['sid'];
TheTextBox.value = TheTextBox.value + text;
if (TheTextBox.value.length == 4) {
if (pinform.pin.value == pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {
document.getElementById("bypass").innerHTML = "Bypass";
document.getElementById("bypass").disabled = false;
document.getElementById("calc").style.backgroundColor = 'red';
TheTextBox.value = '';
return false;
}
}
}
Found the answer by trial and error as usual lol.
i need to add document. in front of pinform.pincheck.value and pinform.pin.value
Thanks for the help offered.
Nick
if (TheTextBox.value.length == 4) {
if (doucment.pinform.pin.value == document.pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {
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.
Alright, so I've been reading and reading and ready about how to run some simple Javascript code when a link has been clicked, but no matter what I try, I can't seem to get it to work!
The idea is that when my link is clicked, it will change color and fill a variable, then when it is clicked again it is to change to another color and return the var back to the state it was (effectively resetting the first click)
Can anyone tell me where I am going wrong here?
Here is my Javascript code:
window.onload = function() {
document.getElementById("atonal").onclick = function() {
var categoryLink=new Array();
var counter;
categoryLink[0] = "empty";
categoryLink[1] = "empty";
categoryLink[3] = "empty";
counter = "0";
if (categoryLink[0]=="empty") {
categoryLink[0] = "atonal";
counter = counter + 1;
stylesheet.insertRule("#atonal {color: #FFFFFF}", 0);
}
if (categoryLink[0]=="atonal") {
categoryLink[0] = "empty";
counter = counter - 1;
stylesheet.insertRule("#atonal {color: #474747}", 0);
}
return false;
}
}
And my HTML:
antonal sound
There are two identical syntax errors in this code; FireBug or equivalent would have showed these to you:
if (categoryLink[0}=="empty") {
That } ought to be a ], of course. Fix those, and your code will work -- or at least, your onclick will be registered and invoked when you expect.
The comments about window.location = "http://www.google.com/"; are correct.
But also, you have a syntax error in your last 2 IF statements:
if (categoryLink[0}=="empty") {
Should be:
if (categoryLink[0]=="empty") {
http://jsfiddle.net/Ekxbu/