How can I display two results in a JavaScript calculator? - javascript

I am building this little calculator where there is only one input field and when user submits the data, I want form to do 2 calculations and display the results in separate divs.
In the first div, I want to whatever user puts in the input area and multiply it by 0.017 (result goes into first div). For the second calculation, I want to multiply the whatever value was put into the input field by 0.170 and display the result in a separate div. Please see the image for visual rep.

Essentially you are creating two values (one calculation for each field) then setting the inside of the display elements (the DIVs) to the values of the calculations:
var someNumber = 10;
var someNumberAfterCalculationOne = someNumber % 4;
var someNumberAfterCalculationTwo = someNumber - someNumberAfterCalculationOne;
document.getElementById("lt_input").innerHTML = someNumberAfterCalculationOne;
document.getElementById("kg_input").innerHTML = someNumberAfterCalculationTwo;
Here is an example of how you might accomplish this:
http://jsfiddle.net/nmbwamtd/3/
This approach is a little ugly, but should get you through to the next step.

Related

JavaScript: How to store, update, and calculate the average and total number of values in a set of user-generated times in seconds

This is a reaction tester project I've been working on
that shows you how fast you click a box or circle that appears randomly.
What I'm having trouble adding are two features: The ability to show the user how many attempts they've made,
and their average speed based on the sum of all times of their tries in seconds divided by their current total number of tries.
I've thought of a couple of different ways to get the number of tries: either counting the number of times the box appears, or since the best way
to record the seconds from each try seems to be to push those seconds into an array and sum them;
getting the length of that array would also give the number of tries.
The two places I'm stuck at are in trying to get the times to be stored into an array and summing them;
plus getting the number of tries and dividing that sum.
I've thought and worked on this at length, and any of my attempts that didn't yield the desired result will likely be confusing.
Here's the code that works:
createdTime=Date.now();
}, time);
}
document.getElementById("box").onclick=function()
{
clickedTime=Date.now();
reactionTime=(clickedTime-createdTime)/1000;
/*I'm trying to take make an array of reaction
times.
here is my last attempt:
recordTime = [];
sumTime = recordTime.push(reactionTime);
console.log(recordtime);
It only shows recordTime array once in the console as [undefined], and does not update the array with new reaction times. What I would expect/ am going for is something like:
first try/iteration>>box appears>>User Clicks>>reactionTime is measured and calculated>>recordTime: recordTime = [0.530];
second try/iteration>>box appears>>User Clicks>>reactionTime is measured and calculated>>recordTime: recordTime = [0.530, 0.511];
third try/iteration>>box appears>>User Clicks>>reactionTime is measured and calculated>>recordTime: recordTime = [0.530, 0.511, 0.353];
fourth try/iteration>>box appears>>User Clicks>>reactionTime is measured and calculated>>recordTime: recordTime = [0.530,
0.511, 0.353,...];
followed by:
sum(recordTime)/(recordTime.length);
(put recordTime result into innerHTML for desired element
id.)
(same for recordTime.length).
I've tried putting it both inside and outside
of the code above it, and none of my attempts have allowed me to add the seconds from reactionTime to an array.
Another option would be to add a "total seconds" span or element on the HTML page, and simply add the current time to the total time.
however, this still has me in much the same situation as to both how to make the javaScript "remember"
previous times, how to count the number of tries, and how to average them.
Thanks to A_A for the answer to my question. All I needed was a const Array=[0]; to store the values a user generated on a click. Thanks, A_A!
If you want to add an element to an array, you should not initialize it again (reactionTimes = []) as this will make it empty. Therefore initialize it in the beginning, and then call push on it.
const reactionTimes = [];
let startingTime;
function start() {
startingTime = Date.now();
}
function stop() {
const reactionTime = Date.now() - startingTime;
reactionTimes.push(reactionTime);
console.log(reactionTimes);
}
<button id="start" onclick=start()>Start</button>
<button id="stop" onclick=stop()>Stop</button>

How do I output a new random number to an HTML doc(via innerText) in JavaScript?

I am doing a simple math game in HTML and JavaScript for school, this is just a small part of it. Basically I have a button that I want to be able to press, and each time I press it I want it to output a new number to the innerText of a div in the HTML document.
Right now I get the random number, but I have to refresh the page to get a new one since it keeps outputting the same one if I press it again.
const mathQuestion = document.getElementById('math-question')
const newNumbers = document.getElementById('new-btn')
newNumbers.addEventListener('click', setQuestion)
function setQuestion () {
mathQuestion.innerText = calc.toString();
console.log(calc);
}
var calc = Math.floor(Math.random() * 100) + 1;
Yes, it's very simple and probably not the easiest or even the correct way to do it, but I am at a loss here.
I suspect I need to run another function for reseting the text or something after ive set the innerText, but I don't really know where to start.
Currently, you only generate the random number once and when you click the button, you set the same number in the HTML. That is why you see the same number irrespective of how many times you click the button.
Number changes on page reload because each time page reloads, new random number is generated.
You need to re-generate the random number every time the button is clicked. To do this, move the random number generation code inside the event handler function and it should work as expected.
function setQuestion () {
var calc = Math.floor(Math.random() * 100) + 1;
mathQuestion.innerText = calc;
}
Also, there's no need to explicitly convert the number into a string.

one js file for calculations

i have a js file (which utilises the jquery framework) that is a simple equation to calculate corresponding values.
JS FILE (sample):
var colorOneRed = parseFloat($('#colorOneRed').text()); ...
var totalRed = (parseFloat(colorOneRed) + parseFloat(colorTwoRed) ...
$('#totalColorRed').text(totalRed); ...
I have the same exact equation multiple times, only the color changes. So the same equation is used for green var colorGreen, blue, purple, etc.
My question is can I write just the one equation to encompass all the variables and #id's
instead writing the same equation over and over.
I tried the id^='totalcolor' method for example, but it will only calculate the one variable. So what I mean is, if #colorOneRed has a value of 40 but #colorOneGreen has a value of 60 it will only calculate the one value for all using the id^=colorOne method.
I'm not sure its even possible but i'm hoping to have one equation that will be able to have a calculation for all the greens and one for all the blues and so on.
Thanks in advance for any help.
I think this is what you are trying to do. Checkout this fiddle. You can always extend this for other color elements.
Put the calculation in one function:
function calc(displayElt, color){
var total=parseFloat($('#colorOne'+color).text()) + parseFloat($('#colorTwo'+color).text())+..
$('#'+displayElt).text(total);
}
calc(totalColorRed,Red);
Wrap your code in a function where you pass in the required DOM elements to perform the calculation:
function calculate(colorOneElement, totalElement) {
var colorOne = parseFloat($(colorOneElement).text()); ...
var total = (parseFloat(colorOneRed) + parseFloat(colorTwoRed) ...
$(totalElemenet).text(totalRed); ...
}
The use as follows:
calculate(document.getElementById("colorOneRed"),
document.getElementById("totalOneRed"));
calculate(document.getElementById("colorOneGreen"),
document.getElementById("totalOneGreen"));
etc ...

How to make a game out of an html table?

I'm basically trying to make a game that involves a grid. Here's what I have so far (it'll help to see the game before I explain what I need to happen):
Javascript (see jsfiddle for html):
var score = 0;
var points = function(val, box) {
var noise = Math.round(Math.round(0.1*val*Math.random()*2) - 0.1*val);
score = score + (val + noise);
var square = document.getElementById(box);
square.innerHTML = val + noise;
square.style.display='block';
setTimeout(function() {
square.style.display='none';
}, 400);
document.getElementById("out").innerHTML = score;
}
http://jsfiddle.net/stefvhuynh/aTQW5/1/
The four red squares at the bottom left of the grid needs to be the starting point in the game. When you click on one of those boxes, you can then travel along the grid by clicking adjacent boxes. Basically, I need to make it so that the player can only travel up, down, left, and right from the box that they just clicked on. I don't want the points function to be invoked when the player clicks on a box that they're not supposed to click on.
Additionally, I need to make it so that the player can't click on another box until 400 ms have elapsed.
I'm relatively new to programming so any help at all would be great. I would also appreciate tips on how to make the program more efficient, if there's a way to do that.
General idea:
I'd suggest having a similar id for all your boxes, such as box_x_y, and storing a list of strings, let's say allowedSquares.
You would then be able to write a function which, upon clicking on a box, would check if it's id is in allowedSquares, and if it is, call points(val, box) then update the contents of allowedSquares to reflect the change of position.
The point of using a standard id convention for all your boxes is that you could write getPosition(box) and getBox(intX, intY) that would parse the id strings to return you the box position, or vice-versa.
You can even make the updateAllowedSquares(clickedBox) function change the color of adjacent boxes to show they're allowed next steps.
EDIT: Some example code:
Disclaimer: these are not the code lines you're looking for.
This is only a starting kit for you, which assumes a 3x3 grid with a single-square bottom right starting position. You will have to adapt this code a bit. Also, I predict something will go wrong concerning going out of bounds. I'll let you think with this a bit, as I prefer giving food for thoughts over complete solutions in those cases...
var allowedSquares = ["box_2_2"]; // Initial list
function decodePositionFromID(boxId) {
return boxId.split("_").slice(1,2);
}
function getIDfromXY(x, y) {
return "box_" + x + "_" + y;
}
function updateAllowedSquaresList(boxID) {
// 1 - We clear the array.
allowedSquares.length = 0;
// 2 - We get the adjacent boxes IDs.
var xyArray = decodePositionFromID(boxId);
var upperBoxID = getIDfromXY(xyArray[0], xyArray[1]-1);
// Rince, repeat, and add some gameboard boundaries checks.
// 3 - We add the new IDs to the list.
allowedSquares.push(upperBoxID, ...);
}
function boxClick(val, boxID) {
// We check if the box is a valid square to play.
if (allowedSquares.indexOf(boxID) != -1) {
points(val, boxID);
updateAllowedSquaresList(boxID);
}
}

Infinite loop when using generic solution to split up carousel contents

Basically, I'm getting an infinite loop and maybe I'm working too hard but I can't see why.
Context:
I'm using a carousel (Bootstrap's). The contents of the carousel is generated and pushed into one carousel slide, then the goal is to take the contents and split it up into multiple slides if the number of items inside surpass a certain pre-defined max-length property (5). I got this working fine for a specific use case of the carousel (a table being spread across the multiple slides if there are more than 5 table rows), but it's not generic enough. What happened is that the JS would take the overflown table rows (i.e. of index 5 and up), create a new slide from a harcoded HTML string in the function (a slide div containing all the markup for the table yet empty) and push those extra rows into it.
To make it more generic, I've decided to use classes like carousel_common_list and carousel_common_item which would be applied to the tbody and trs in the case I've explained. Then, I've to handle the template in a decoupled way. What I've tried to do is, take a clone of the original sole slide, empty the carousel_common_list and push any overflown carousel_common_items into it, and so on. But I get an infinite loop.
Code
What I've called a slide so far is called an item in the code (to match Bootstrap's carousel's item class for slides).
var carousels = $('div.carousel'),
carouselCommonListClass = 'carousel_common_list',
carouselCommonItemClass = 'carousel_common_item',
items_per_slide = 5;
$.each(carousels, function (index, element) {//for each carousel
var $carousel = carousels.eq(index),
$items = $carousel.find('.item');
var getItemTemplate = function ($item) {
$copy = $item.clone();//take the html, create a new element from it (not added to DOM)
$copy.find('.' + carouselCommonListClass).empty();
$copy.removeClass('active');
return $copy;
}
var splitUpItem = function ($item, $itemTemplate) {
var $bigList = $item.find('.' + carouselCommonListClass), group;
while ((group = $bigList.find('.' + carouselCommonItemClass + ':gt(' + (items_per_slide - 1 ) + ')').remove()).length) {
var $newItem = $itemTemplate;
$newItem.find('.' + carouselCommonListClass).prepend(group);
$newItem.insertAfter($item);
splitUpItem($newItem, $itemTemplate);//infintely called
}
}
//foreach item
$.each($items, function (item_index, item_element) {//for each slide, in each carousel
var $item = $items.eq(item_index);
splitUpItem($item, getItemTemplate($item));
});
});
FYI, this works like expected when the line marked with //infintely called is commented out; i.e. splits one oversized slide into one slide of items_per_slide length and another slide (which could be over items_per_slide in length if the original sole slide was over items_per_slide * 2 in length.
Also, I took this answer and modified it for the contents of splitUpItem().
Note:
I know it's not the most usable or accessible solution to split tables, lists, etc. over multiple slides like I am, but if you've a better idea answer my open question on that.
You're not getting an infinite loop per se, in that you're not infinitely stuck in the same while loop. As you mention, when you remove the //infinitely called line you're fine. The first pass through that while loop, the length you compute will equal the number of items (with gt:(4)) in all the lists in $item. You then remove all those items, so the next pass through will have that number equal to 0. This will always be the behaviour of that loop, so it really doesn't need to be a loop, but that's not the main problem.
The problem is that it's a recursive call. And the only guard you have against making the recursive call infinite is the condition in your while loop, but that condition will always be met the first pass through. In fact, if $item has 5 lists, each with 3 items with gt:(4), then $newItem will have 5 lists, each with 5 x 3 = 15 items. So when splitUpItem gets called on $newItem, the condition in your while loop will again first be non-zero. And then it'll get called again, and that number will be 5 x 15 = 75. And so on. In other words, you're recursively calling this function, and your guard against this call being made infinitely many times is to check that some number is 0, but the number there will actually grow exponentially with each recursive call of splitUpItem.
Hope that answers your question about why it's "infinitely looping." Gotta get to work, but I'll try to suggest a better way to split up the slides tomorrow if no one else has by then.

Categories