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>
Related
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>
I want to calculate the Standard Deviation of the data, mode, and median so I was wondering if someone could help me out with these functions?
I've tried calling math.js but it doesn't work.
https://www.npmjs.com/package/stats-lite
//
// function myFunction(){
// alert("Hello Javatpoint");
//
// }
//
// function myFunction2(){
// alert("Hello Nasser ");
//
// }
function mean(values){
var total = 0,
i, results;
var onlyNumbers = values.replace(/\D/g, '');
for (i = 0; i < onlyNumbers.length; i += 1) {
total += parseInt(onlyNumbers[i]);
}
results = total / onlyNumbers.length;
document.getElementById("meanOutput").innerHTML = results;
}
function mode() {
document.getElementById("modeOutput").innerHTML = "Fahad!";
}
function median() {
document.getElementById("medianOutput").innerHTML = "Nasser";
}
function stdv() {
document.getElementById("stdvOutput").innerHTML = "Alqahtani";
}
<!DOCTYPE html>
<html>
<script src="script.js"></script>
<body>
Mean: <input type="text"
id="meanText" >
Median:<input type="text"
id="medianText" >
Mode:<input type="text"
id="ModeText" >
Standard Deviation of the data:<input type="text"
id="STDV" >
<p id="meanOutput"></p>
<p id="modeOutput"></p>
<p id="medianOutput"></p>
<p id="stdvOutput"></p>
<button onclick="mean(document.getElementById('meanText').value); median(); mode(); stdv();">Calculate</button>
</body>
</html>
I expect to see correct results for median, mode and Standard Deviation of the data.
is this my calculate mode way, i used a condicional if whole numbers of array is differens then return the Math.min:
var arrayP = [4,2,3,6,1,10] // example array
console.log(Mode(arrayP)) // example result
// function calculate mode
const Mode = arr =>{
var uniques = Array.from(new Set(arr)).map(r=>[r,0])
if (uniques.length == arr.length){return Math.min(...arr)}
for(q in arr){
for(j in uniques){
if(arr[q] == uniques[j][0]){
uniques[j][1] += 1
}
}
}
uniques.sort((a,b)=> b[1]-a[1])
return uniques[0][0]
}
We need to make a class called Series with two methods
triNums - function that returns you a triangular series by the number it recives eg: if the function gets 5 - 1, 3, 6, 10, 15
fibNums - function that returns you a fibonacci sequence by the number it
recives eg: if the function gets 5 - 0,1,1,2,3,5
Each of the functions need to be executed when pressing on a button (fibo)(tri) and each element of the result should be displayed on a button
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
addBtns(triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num.value; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
Enter Name <input id="name" placeholder="Enter name"></input>
<button onclick="sayHello()">Click me</button>
<h1 id="hello"></h1>
<input id="num"></input>
<button onclick="tri()">triangular</button>
<div id="feed"></div>
</body>
</html>
You made some mistakes:
you pass #num.value to triNums, which is a Number, and then you try to access its value, which is unneccessary and impossible.
You cannot call tri() as it is part of a Series instance. You could do (new Series).tri() .
Same applies for inner function calls, you must access them via this :
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
this.addBtns(this.triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
function start(){
(new Series).tri();
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
<div id="feed"></div>
<input id="num" />
<button onclick="start()">Start</button>
</body>
</html>
Below is my code. I need to sort the array after the user input but can't figure out how to make that happen. I have tried several different things but nothing has worked including data.sort() and data.sort(function(a,b) { return a - b; }); but neither seems to be working. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Input integers into the array and then search the array to see if your input is present!</h1>
<p id="data">[]</p>
<input id="inputNumber" value="0" /> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0" /> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
for (var i = 0; i < 5; i++) {
data.push(prompt('enter integer ' + (i + 1)));
}
alert('Full array: ' + data.join(', '));
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for (var i = 0; i < data.length; i++) {
if (data[i] == toFind) return alert("found at " + i);
}
return alert("That number was not found");
}
function refresh() {
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>
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>