Can someone please help implement something in my javascript project? #http://codepen.io/urketadic/pen/YpLgBX
I want number to turn red if its wrong and not in sequence with pi. Its really difficult for me to keep count and compare with everything.
I've tried a lot of this and at the end I've come up with this code:
var count = 0;
// color the mistake right away
$("#inputsm").keyup(function(event) {
var pressed = event.key;
answer = $("#inputsm").val();
pisub = pi.substr(input,answer.length)
if (pressed!=="Backspace"&&pressed!=="Delete") count++;
else count--;
console.log(count);
});
I'm just confused, i don't know how i can do this. Also does text area even allow numbers to turn red? I've tried adding jquery css as well but it doesn't work. Can someone write it in their own codepen and post a link?
Take a look at this fiddle: https://jsfiddle.net/ebv5n64j/2/
I've put together something that does basically what you are trying to do. You can modify it from there but that is the basic concept. I designed mine to not let the user continue until they get it right, but you could easily change that.
This is a snippet, but jsfiddle has the complete working version:
// If it's a delete command
if(code === 8){
if(!$("#wrong").length > 0)
inputCount = (inputCount === 0 ? 0 : --inputCount);
$("#pi span").last().remove();
console.log(inputCount);
} else if (code >= 48 && code <= 57) {
var inputNumber = code - 48;
var numSpan;
$("#wrong").remove();
numSpan = $("<span>"); // make a new one
// Append the number
numSpan.text(inputNumber);
numSpan.removeClass("incorrect");
if(String(inputNumber) === piDigits[inputCount]){
numSpan.addClass("correct");
inputCount++;
} else {
numSpan.attr("id", "wrong");
}
$("#pi").append(numSpan);
placeCaretAtEnd(this);
}
So I looked at your pen and thought that you were somewhat over-complicating the solution. I think a better way would be to compare the string of the input textarea with the substring of pi. Anyways, here's the fixed code and I've linked to the pen with the working version.
By the way, you mention in the description that if they want to start at the number 4 in 3.14 they should type in 1 (for index 1), but you take their input and subtract it by 1, so it essentially starts them off at 1 instead of 4, if they typed in 1.
$("#inputsm").keyup(function() {
var thisLength = parseInt(input) + $(this).val().length - 1;
if($(this).val().trim() === pi.substring(parseInt(input), thisLength)) {
console.log("good so far!");
$(this).removeAttr('style');
} else {
console.log("ahhh no good!");
$(this).css('background', 'red');
}
});
http://codepen.io/msafi/pen/dOKogK/
Related
I've added an AC button to my JS calculator which resets the variables and displays 0 in the displayArea.
However when the user starts typing their first number the 0 stay's so it shows 03 instead of 3 etc - this doesn't impact the calculation.
I've tried to remove this using parseInt and an IF statement however it doesn't seem to work.
My best attempt so far is:
<p id="result-display"> </p>
let displayArea = document.getElementById('result-display');
else if (displayArea.innerHTML = 0) {
buttonNumber = Number(e.target.innerText);
displayValue = buttonNumber;
displayArea.innerHTML = parseInt(displayArea.innerHTML += displayValue);
}
If I change the 0 to a string e.g. '0' it works but then also stops the user entering multiple number values e.g. 56 would show as 5 etc.
My JSFiddle is: https://jsfiddle.net/mh85skxv/3/
Add the following line at the end of your calculate function:
displayArea.innerHTML = Number(displayArea.innerHTML);
This will convert the content of the displayArea to a number, eliminating any leading zero.
If you don't want the 0 to appear when pressing AC just replace this line:
displayArea.innerHTML = 0;
with this:
displayArea.innerHTML = '';
Then parse your number like this in order to avoid NaN:
Number(displayArea.innerHTML) || 0;
Not sure of the exact solution, but here's a few tips from your question and your Fiddle code:
else if (displayArea.innerHTML = 0) { can't work because you need == or ===. Using only the equal sign doesn't check the value of displayArea.innerHTML but assigns it to 0.
Also innerHTML is not usually equal to 0...maybe try innerHTML.length or something ?
On your fiddle code I notice that you use statements like return firstNumber = .... This is incorrect; instead, declare your variable firstNumber at the top, and for each switch case write something like:
firstNumber = //whatever you want
break; //this will ensure your code stops there
Hope this helps,
I am making a basic calculator in javascript. My addition and multiplication buttons work well. However, my subtraction and division functions are not working.
When I click subtract, for some reason that I can't figure out (I've been scratching my head forever), it automatically converts the number in the output to a negative number.
And for division, I can't seem to get the logic down to divide the first number I enter by the second number I enter.
Here is my basic calculate function:
function calculate() {
if (operator == 'add') {
runningSum += windowNum;
} else if (operator == 'subtract') {
runningSum -= windowNum; // automatically converts windowNum to negative, unclear why
} else if (operator == 'multiply') {
if (runningSum == 0) {
runningSum = 1;
}
runningSum *= windowNum;
} else if (operator == 'divide') {
// ever mutation tried comes up with wrong result
}
outputWindow.textContent = Number((runningSum).toFixed(5));
operatorClicked = true;
numClicked = false;
document.querySelector('#btnAdd').classList.remove('operatorClicked');
console.log('windowNum: ' + windowNum);
console.log('runningSum: ' + runningSum);
}
Because my project is rather big, I've included a link to it in codepen here: https://codepen.io/CDLWebDev/pen/mdJgbeG
I checked your codepen and changed a few things. Mainly, you were performing calculations whenever a click to the operation signs was made, which is not really something you want to do, since you can't perform operations when you don't know what number will come next. On calculators, calculations are actually performed when you press the "equals" sign.
What really has to happen and what I've done in the code below is keep the number you just pressed as your runningSum and choose the operation, then when you press equal you have all the info you need.
https://codepen.io/VPR/pen/poJBzXP
function clickOperatorBtn() {
if (numClicked) {
if (target == document.querySelector("#btnDivide")) {
operator = "divide";
runningSum = windowNum;
clearWindow();
} else if (target == document.querySelector("#btnMultiply")) {
operator = "multiply";
runningSum = windowNum;
clearWindow();
} else if ...
I assume this is a learning exercise, so keep it up, but I think the logic behind your code could improve, when you're done try googling some tutorials on calculators, you'll find many which walk you through the steps performed and the logic behind it.
I tried your code and the function calculate is ran every time you change the operator. That means that when, initially, click on the '-' sign you will trigger that function. Bear with me:
else if (operator == 'subtract') {
// windowNum == 3 - for example
// runningSum == 0
runningSum -= windowNum;
// result will be 0 - 3 == -3
This means that if you do the same with say, 7. You'll be doing -3 - 7 == -10
About the division:
This is also happening, so when you do something like clicking 8 and then division, what you're doing is 0 / 8 (which apparently results in 1).
Hope this helps!
I'm doing a simple project with javascript and it requires me to get a value out of an HTML text input with javascript. In the following code I've found that nothing after line 6 works and I have no idea why. This has been driving me crazy for like two hours and I'm kind of at my wits end. Please help!
function letsPlayAGame() {
var answer = Math.floor(Math.random() * 100 + 1);
var guess = document.getElementByID("theinput").value;
if (Number.isInteger(guess) == false) {
document.getElementByID("label").innerHTML =
"Please enter a number between 1 and 100!";
} else if (guess < 1 || guess > 100) {
document.getElementByID("label").innerHTML =
"Please enter a number between 1 and 100!";
} else {
alert("not this part");
}
}
It should be:
document.getElementById
instead of
document.getElementByID
as Javascript is case sensitive.
Hello I have some experience with javascript but I would really like to learn how to program in C and one of the ways I am trying to learn is by converting some simple javascript code into C. My current attempt at converting a simple program compiles without any errors however doesn`t produce the answer I want it to. The javscript code produces the correct answer and I wrote it to solve project euler problem number 5 which can be found here: https://projecteuler.net/problem=5
Here is the working js code:
var number = 2520;
var count = 1;
var solved = false;
while (!solved) {
if (number % count === 0) {
if (count === 20) {
solved = true;
console.log(number);
} else {
count++;
}
} else {
number++;
count = 1;
}
}
Here is the C conversion which does not work:
#include <stdio.h>
int main () {
unsigned int number = 2520;
unsigned int count = 1;
unsigned int solved = 0;
while ((solved = 0)) {
if (number % count == 0) {
if (count == 20) {
solved = 1;
printf("%number");
} else {
count++;
}
} else {
number++;
count = 1;
}
}
return 0;
}
while ((solved = 0)) {
You can use the same syntax you would use in js here, namely, while (!solved), or ==, but just = is an assignment.
printf("%number");
Doesn't mean what you think it means, which is why it's not an actual error (%n is a distinct specifier, and with no corresponding input, you'd get umber as the output). To reproduce console.log() you'd want:
printf("%d\n", (int)number);
Or
printf("%u\n", number);
Notice the explicit \n, since printf() does not add a newline otherwise.
Replace
while (solved = 0)
with
while (!solved)
and
print("%number")
with
print("%u\n",number)
I know its already answered, but you should know why.
while ((solved = 0))
Will actually set solved to 0 AND return 0 (which is interpreted as false). So the while loop is exited right away.
printf also takes a pretty strictly formatted string for the first one (just typeing what makes sense is guarenteed to be wrong). The compiler has know way to know what is inside the string is anything other than a string (C++ has (almost) NO reflection, unlike javascript: your written code dissapears into ones and zeros). printf needs to take number in as the second argument. Try printf("%i\n",number);. That says "Print an integer followed by a newline. The integer's value is number."
Welcome to C! Your biggest problem going into is is going to be my biggest problem with Java Script: C is strictly typed with no reflection, while javascript has no types with almost everything relying on some sort of reflection.
jsFiddle: http://jsfiddle.net/Mw4j2/6/
Trying to change attributes to a selector if the seconds count is 10 or under.
I'm using
var returnSecondsNumber = $('.countdownSecond > .countSeconds > .position:first-child > .digit').text() + $('.countdownSecond > .countSeconds > .position:nth-child(2) > .digit').text();
To grab the numbers from both spans and returns it as 16/15/14/etc.
Now I need do something if this numeric is under 10.
e.g.
if (returnsSecondsNumber <= 10)
{ $(this).addClass('urgent');
}, else { //do something
}
I've tried taking a look at parseInt with no success. Any help would be much appreciated!
Thanks.
Two things:
First, you need to move the code that constructs "returnSecondsNumber" into the callback function(s) of whichever timers you want to monitor.
Second, just use parseInt():
var numericVal = parseInt(returnsSecondsNumber, 10);
if (!isNaN(numericVal) && numericVal < 10) {
// do whatever
}
Try
if(!isNaN(parseInt(returnsSecondsNumber )) && returnsSecondsNumber < 11)
//Do stuff...
One thing to keep in mind is that if the value of returnsSecondNumber is a starts with a number that will be returned instead of NaN