How to add a variable's value to an array function? - javascript

I'm trying to add the random number to the array which is assigned to a function that keeps adding the numbers together.
function getMiNumber(number){
var value = Math.floor(Math.random() * 10) + 1 ;
value.push(value.value);
var myArray = someCalc([0]);
console.log(myArray);
function showMe(val) {
var presentMe = document.getElementById('someId');
presentMe.innerHTML = val;
}
showMe(myArray);
function someCalc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}
}

UPDATE
Reread the question and determined that a cumulative total is desired so this demo will:
Generate a random number 1 to 10.
Display that number.
Add that number to an array.
Display that array.
Add all of the array's elements.
Display that total.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>34562147</title>
<style>
html,
body {
font: small-caps 400 16px/1.4 'Source Code Pro';
}
fieldset {
border: 2px inset grey;
border-radius: 10px;
}
legend {
font-size: 1.3rem;
}
</style>
</head>
<body>
<fieldset>
<legend>Random Array Total</legend>
<input id="btn1" type="button" onclick="rand()" value="Random" />
<br/>
<label for="out0">Next:
<output id="out0"></output>
</label>
<br/>
<label for="out1">Array:
<output id="out1"></output>
</label>
<br/>
<label for="out2">Total:
<output id="out2"></output>
</label>
</fieldset>
<script>
var xArray = [];
function rand() {
var ran1 = Math.floor(Math.random() * 10) + 1;
var out0 = document.getElementById('out0');
var out1 = document.getElementById('out1');
var out2 = document.getElementById('out2');
out0.value = ran1;
xArray.push(ran1);
out1.value = xArray;
out2.value = calc(xArray);
}
function calc(xArray) {
var total = 0;
for (var i = 0; i < xArray.length; i++) {
total += xArray[i];
}
return total;
}
</script>
</body>
</html>
OLD
The array is pre-determined in this demo var xArray = [23, 8, 90, 7];
function randomNumber(xArray){
var value = Math.floor(Math.random() * 10) + 1 ;
xArray.push(value);
return xArray;
}
var xArray = [23, 8, 90, 7];
var total = calc(randomNumber(xArray));
console.log(total);
function output(total) {
var out1 = document.getElementById('out1');
out1.value = total;
}
function calc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}
output(total);
<output id="out1"></output>

Related

Create triangle and square pattern with input js

I started creating a program in where an input from a user is needed, then, depending on the input, will display either a right triangle or square (triangle for even, square for odd) The pattern will be in descending order starting from the input number. However, my code does not yield any output.
Output:
triangle (3 is the input number)
3 3 3
2 2
1
square (3 is the input number)
3 3 3
2 2 2
1 1 1
Is there something missing in my code? Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<script>
function myFunction() {
var number;
console.info("Number:" + number);
if (number %2 == 0) {
var line = document.getElementById("list")
for (let n = 1; n <= number; --i) {
let line = "";
for (let r = 1; r <= n; ++j) {
line += (j + " ");
}
document.getElementById("line");
}
} else {
var line = document.getElementById("list")
for (let n = 1; n <= number; i++) {
let line = "";
for (let r = 1; r <= number; j++) {
line += (j + " ");
}
document.getElementById("line");
}
}
}
</script>
</head>
<body>
</br>
Enter the number : <input id="number" type="number"/>
<br />
<button onclick="myFunction()">Print</button>
<div id="line">
</body>
</html>
you have some errors over your code , first you don't see any content because you never create a dom element and append to html ,then you don't read the value of the input, your loops have a some errors of undefined variables,and put always your js script at the end of the body, because you need to all html elements be rendered before your js be executed for dont have undefined value when you do you document.getElementById, i made a full example with a new code that achieve the goals , just read it and you will notice the difference and the errors that you have , peace dog!
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.clear {
clear: both;
}
.float-left {
float: left;
height: 20px;
width: 20px;
vertical-align: middle;
line-height: 20px;
text-align: center;
border: 1px solid green;
}
.triangle {
-moz-transform: skew(45deg);
-webkit-transform: skew(45deg);
transform: skew(45deg);
}
</style>
</head>
<body>
</br>
Enter the number : <input id="number" type="number" />
<br />
<button onclick="init()">Print</button>
<div id="figure">
</div>
<script>
let figureContainer = document.getElementById('figure');
function drawLine(number, lengthOfLine, typeOfFigure) {
for (let i = 0; i < lengthOfLine; i++) {
let numberIOfLine = document.createElement("div");
numberIOfLine.innerHTML = number;
if (typeOfFigure === "triangle") {
numberIOfLine.className = "float-left ";
} else {
numberIOfLine.className = "float-left";
}
figureContainer.appendChild(numberIOfLine);
}
let clearLine = document.createElement("div");
clearLine.className = "clear";
figureContainer.appendChild(clearLine);
}
function drawSquare(number) {
for (let i = 0; i < number; i++) {
drawLine(number - i, number, "square");
}
}
function drawTriangle(number) {
for (let i = 0; i < number; i++) {
drawLine(number - i, number - i, "triangle");
}
}
function init() {
figureContainer.innerHTML = "";
let number = document.getElementById("number").value;
if (number % 2 === 0) {
drawSquare(number);
} else {
drawTriangle(number);
}
}
</script>
</body>
</html>

Uncaught ReferenceError: main is not defined

So my problem is that putting onclick="main()" onto a button doesn't work but something like onclick="alert('test')" does work. When I look in the console, it throws Uncaught ReferenceError: main is not defined when I press the button.
I have tried putting all the functions that aren't main() inside of main() but that didn't work. I've also tried putting semicolons after all the functions thinking that I just made up the fact that you don't have to put a semicolon after a function.
I'm confused because I copy/pasted another JavaScript program of mine and edited it to make this and that one works fine.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
<style>
/*----- START OF STYLESHEET -----*/
*, :before, :after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/*body {
margin : 0;
*/}
/*-----END OF STYLESHEET-----*/
</style>
<script>
//----- START OF SCRIPT -----//
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shuffle-list() {
for(var shuffleent = 0; shuffleent > list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display-list() {
var state = "";
for(displayent = 0; displayent > list.length; displayent = displayent + 1) {
for(displayentvalue = 0; displayentvalue > list[displayent]; displayentvalue = displayentvalue + 1) {
state = state + "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
Sleep(1000);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display-list();
// Shuffle sorted list
// Sort
//while(isSorted === false) {
//}
}
//-----END OF SCRIPT-----//
</script>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
some error in you code:
"}"
'-' in the function name.
after fixed the error, the code worked
You should not use a - while naming your function but instead you can use these.
An underscore and replace the -.
display-list() to display_list()
Use CamelCase.
display-list() to displayList().
Function names can contain letters, digits, underscores, and dollar signs but not dash
sign
There are so many mistakes in your code.
There is no Sleep function in the JS.
You can't have - or whitespaces in the function names.
You are never going to enter in this loop for(displayent = 0; displayent > list.length; displayent = displayent + 1) you had to use < instead >
Where are you using valuecount and isSorted
In the CSS } which shouldn't be there
I edited some of your code to make it work.
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shufflelist() {
for (var shuffleent = 0; shuffleent < list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display_list() {
var state = "";
for (displayent = 0; displayent < list.length; displayent = displayent + 1) {
for (displayentvalue = 0; displayentvalue < list[displayent]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
Re Wrote the logic of your code
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
list[value2] = [list[value1], list[value1] = list[value2]][0];
}
// Shuffle list
function shufflelist() {
list.forEach((element, index) => {
swap(index, randint(0, list.length))
})
}
// Display list
function display_list() {
var state = "";
list.forEach((element, index) => {
for (displayentvalue = 0; displayentvalue < list[index]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state += "\n"
})
console.log(state);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
shufflelist();
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>

Adding the result of separate results

Thanks in advance for any replies. I am new to JavaScript and have got this far in calculating 2 results that I require. My question is how do I add both results together?
Please see first result below:
$(document).ready(function() {
function checkSum(e) {
var result = 0;
$(".checksum").each(function() {
var i = 0;
if ($(this).val() != "") {
i = parseFloat($(this).val());
}
result = result + i;
});
$("#resultsum").html(result * 60.60);
}
checkSum();
$(".checksum").bind("keyup", checkSum);
});
and this is the second:
$(document).ready(function() {
function checkSum2(e) {
var result2 = 0;
$(".checksum2").each(function() {
var j = 0;
if ($(this).val() != "") {
j = parseFloat($(this).val());
}
result2 = result2 + j;
});
$("#resultsum2").html(result2 * 14.88);
}
checkSum2();
$(".checksum2").bind("keyup", checkSum2);
});
Just add one line in the end of functions:
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
$(document).ready(function() {
function checkSum(e) {
var result = 0;
$(".checksum").each(function() {
var i = 0;
if ($(this).val() != "") {
i = parseFloat($(this).val());
}
result = result + i;
});
$("#resultsum").html(result * 60.60);
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
}
checkSum();
$(".checksum").bind("keyup", checkSum);
function checkSum2(e) {
var result2 = 0;
$(".checksum2").each(function() {
var j = 0;
if ($(this).val() != "") {
j = parseFloat($(this).val());
}
result2 = result2 + j;
});
$("#resultsum2").html(result2 * 14.88);
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
}
checkSum2();
$(".checksum2").bind("keyup", checkSum2);
});
I've combined your snippets in to one to remove the redundant code you have. This approach will allow you to add more checksums in future (.checksum3?) and also makes sure your calculation logic is same for all.
The result is calculated in to new element whenever any of the checksums change. Try the snippet below:
// function to calculate checksum
// used for both individual results as well as for total
function calcChecksum(elements) {
let result = 0;
elements.each( function(index, ele) {
result = result + (parseFloat($(ele).val()) || 0)
});
return result;
}
// update total result
function updateTotal() {
let total = calcChecksum($('.result'));
$('#resultsum_total').val(total);
}
$(document).ready(function() {
// generate function for each set of checksum inputs
function genCheckSumFn(inputSel, outputSel, multiplier) {
return () => {
const result = calcChecksum($(inputSel));
$(outputSel).val(result * multiplier);
updateTotal();
}
}
//checkSum bindings
$(".checksum").bind("keyup",
genCheckSumFn('.checksum','#resultsum',60.60)
);
$(".checksum2").bind("keyup",
genCheckSumFn('.checksum2','#resultsum2',14.88)
);
// trigger initial calculation
$(".checksum").trigger('keyup');
$(".checksum2").trigger('keyup');
});
.checksum,
.checksum2{
display: block;
}
.box {
padding:10px 0px;
}
.box div {
margin-top:5px;
}
.box.results input {
color: #FFA500;
border:0px;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
Checksum
<input class="checksum" value="10">
<input class="checksum" value="5">
Checksum(2)
<input class="checksum2" value="20">
<input class="checksum2" value="15">
<div>
<div class="box results">
<div> Resultsum:
<input id="resultsum" class="result" readonly> </div>
<div> Resultsum(2):
<input id="resultsum2" class="result" readonly> </div>
<div> Resultsum(Total): <input id="resultsum_total" readonly> </div>
</div>

Javascript calculate function not calculating

I have recently been working on a project that has resulted in countless hours of frustration. The task is to create a Webpage that calculates a user's total cost depending on the different radio buttons / check boxes they select.
So, assuming all my other functions and constants are correct, is there anything wrong with my function or the calling of my function.
HTML
<input type = "button" value = "Submit" onclick="calculate();">
<table>
<tr><td>Workshop Total:</td> <td><div id="divWorkshopTotal"></div></td></tr>
<tr><td>Lodging Total:</td> <td><div id="divLodgingTotal"></div></td></tr>
<tr><td>Discount Amount:</td> <td><div id="divDiscount"></div></td></tr>
<tr><td>Sales Tax Amount:</td> <td><div id="divSalesTaxAmount"></div></td></tr>
<tr><td>Total Due:</td> <td><div id="divTotal"></div></td></tr>
</table>
JavaScript
function $(elementName){
return document.getElementById(elementName);
}
function calculate(){
clearOutput();
if (checkWorkshopSelected() > 3){
$("divWorkshopError").innerHTML = "* Selected workshops exceeds maximum of " + MAXIMUM_WORKSHOPS_SELECTED;
return;
} else if (checkWorkshopSelected() == 0){
$("divWorkshopError").innerHTML = "* No workshop(s) selected";
return;
}
var workshopCost = calculateWorkshopTotalCost();
var lodgingCost = calculateLodgingCost();
var subtotal = workshopCost + lodgingCost;
var discountRate = calculateDiscountRate();
var discountAmount = subtotal * discountRate;
if ($("chkTaxExempt").checked == false){
var salesTaxAmount = (subtotal - discountAmount) * SALES_TAX_RATE;
}
var totalCost = subtotal - discountAmount + salesTaxAmount;
$("divWorkshopTotal").innerHTML = workshopCost;
$("divLodgingTotal").innerHTML = lodgingCost;
$("divDiscount").innerHTML = discountAmount;
$("divSalesTaxAmount").innerHTML = salesTaxAmount;
$("divTotal").innerHTML = totalCost;
}
Please check out the code and only ask small doubts in comments. Otherwise please make a new question.
var SALES_TAX_RATE = 0.1,
MAXIMUM_WORKSHOPS_SELECTED = 3;
var data = {
productA: 10,
productB: 20,
productC: 25,
};
var prod = document.getElementsByClassName('prod'),
tax = $("tax"),
workshopTotal = $("workshopTotal"),
lodgingTotal = $("lodgingTotal"),
discount = $("discount"),
salesTaxAmount = $("salesTaxAmount"),
total = $("total"),
workshopError = $("workshopError"),
out = document.getElementsByClassName('out');
$("inputButton").addEventListener("click", calculate);
clearOutput();
function $(elementName){
return document.getElementById(elementName);
}
function calculate () {
clearOutput();
if (checkWorkshopSelected() >= MAXIMUM_WORKSHOPS_SELECTED) {
workshopError.innerHTML = "* Selected workshops exceeds maximum of " + MAXIMUM_WORKSHOPS_SELECTED;
return;
} else if (checkWorkshopSelected() == 0) {
workshopError.innerHTML = "* No workshop(s) selected";
return;
}
var workshopCost = calculateWorkshopTotalCost();
var lodgingCost = calculateLodgingCost();
var subtotal = workshopCost + lodgingCost;
var discountRate = calculateDiscountRate();
var discountAmount = subtotal * discountRate;
var salesTax = 0;
if (tax.checked == false){
salesTax = (subtotal - discountAmount) * SALES_TAX_RATE;
}
var totalCost = subtotal - discountAmount + salesTax;
outputPrice(workshopTotal, workshopCost);
outputPrice(lodgingTotal, lodgingCost);
outputPrice(discount, discountAmount);
outputPrice(salesTaxAmount, salesTax);
outputPrice(total, totalCost);
}
function clearOutput () {
for (var i=0; i<out.length; i++) {
var o = out[i];
o.innerHTML = "0,00"
}
workshopError.innerHTML = "";
}
function checkWorkshopSelected () {
var s = 0;
for (var i=0; i<prod.length; i++) {
var p = prod[i];
if (p.checked) s += 1;
}
return s;
}
function calculateLodgingCost () {
return 5;
}
function calculateWorkshopTotalCost () {
var t = 0;
for (var i=0; i<prod.length; i++) {
var p = prod[i];
if (p.checked) t += data[p.id];
}
return t;
}
function calculateDiscountRate () {
return 0.05;
}
function outputPrice (e, p) {
e.innerHTML = p.toFixed(2);
}
p {
line-height: 14px;
width: 200px;
}
#inputButton {
height: 32px;
margin-bottom: 10px;
}
#workshopError {
color: red;
float: right;
margin-bottom: 20px;
}
.prod + label {
font-weight: bold;
}
.out {
display: inline-block;
padding: 4px 12px;
margin: -6px 0;
background: #fff;
border: 1px solid #999;
border-radius: 3px;
font-family: monospace;
float: right;
}
.out:before {
content: "$";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p><input type="checkbox" id="productA" class="prod"><label>Workshop A - 10</label></p>
<p><input type="checkbox" id="productB" class="prod"><label>Workshop B - 20</label></p>
<p><input type="checkbox" id="productC" class="prod"><label>Workshop C - 25</label></p>
<p><input type="checkbox" id="tax"><label>Tax 10%</label></p>
<p><input id="inputButton" type="button" value="Submit"><label id="workshopError"></label></p>
<p><label>Workshop Total:</label><span class="out" id="workshopTotal"></span></p>
<p><label>Lodging Total:</label><span class="out" id="lodgingTotal"></span></p>
<p><label>Discount Amount:</label><span class="out" id="discount"></span></p>
<p><label>Sales Tax Amount:</label><span class="out" id="salesTaxAmount"></span></p>
<p><label>Total Due:</label><span class="out" id="total"></span></p>
</body>
</html>

code that displays words, JS Jquery

Code Link: http://jsbin.com/lozifokuzi/1/edit?html,js,output should display 16 words but it displays only 15 words (The words written in Hebrew).
The code is written in languages ​​JavaScript and jQuery.
$(document).ready(function () {
// creat array of objects, DetermineIDs
var words = new Array(16);
for (var i = 0; i < words.length; i++) {
words[i] = new Object();
words[i].id = i + 1;
}
//insert into objects words
words[0].word = "קוף";
words[1].word = "קוף";
words[2].word = "אריה";
words[3].word = "אריה";
words[4].word = "נמר";
words[5].word = "נמר";
words[6].word = "טלפון";
words[7].word = "טלפון";
words[8].word = "מחשב";
words[9].word = "מחשב";
words[10].word = "מקלדת";
words[11].word = "מקלדת";
words[12].word = "אוגר";
words[13].word = "אוגר";
words[14].word = "עכבר";
words[15].word = "עכבר";
//Determine locations
var ret=Random(loc);
var random = 0;
for (var i = 0; i < words.length; i++) {
words[i].loca=ret[0];
loc=ret[1];
ret = Random(loc);
}
//write the words
for (var i = 0; i < 16; i++) {
$("#c" + (words[i].loca)).html(words[i].word);
}
});
function RandomC(ezer, random) {
for (var i = 0; i <= 16; i++) {
if (ezer[i] == random) {
return true;
}
}
return false;
}
function Random(lq) {
var ezer = new Array(16);
for (var i = 0; i < 16; i++) {
ezer[i] = lq[i];
}
var random = 0;
while ((random < 1 || random > 17) || RandomC(ezer, random)) {
random = parseInt(Math.random() * 100);
}
for (var i = 0; i < lq.length; i++) {
if (lq[i] == null) {
ezer[i] = random;
break;
}
}
var arr = new Array(2);
arr[0] = random;
arr[1] = ezer;
return arr;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<article>
<div id="l1">
<p id="c1"></p>
<p id ="c2"></p>
<p id="c3"></p>
<p id="c4"></p>
</div>
<div id="l2">
<p id="c5"></p>
<p id="c6"></p>
<p id="c7"></p>
<p id="c8"></p>
</div>
<div id="l3">
<p id="c9"></p>
<p id="c10"></p>
<p id="c11"></p>
<p id="c12"></p>
</div>
<div id="l4">
<p id="c13"></p>
<p id="c14"></p>
<p id="c15"></p>
<p id="c16"></p>
</div>
</article>
</body>
</html>
Can anyone help?
You have 17 in funciton Random() while loop:
while ((random < 1 || random > 17) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
make it 16:
while ((random < 1 || random > 16) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
You problem is that you have 16 element from 1 to 16, and your random function gives 16 random numbers from 1 to 17, in case returned range has number 17 it lacks something from 1 to 16, which means your p element of that nubmer doesn't get filled with content.

Categories

Resources