Why does my change button not work? - javascript

I am quite new to javascript and I am learning more about HTML5, Javascript and CCS3.
The task I have been given:
Create a chess board where you use JavaScript to write the cells (8x8), and then use nth-child to change the background color in CSS.
As you can see I have done that, I don’t know if I have done it in a good way, but I am now going to add a button that change the sides (black and white side). I have tried to solve it by creating var with boolean value, if it’s true it will load one function, and if it’s false another. It works in loading the page, but the change button does not work. What have I done wrong?
HTML and JavaScript:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="ccsO2.css">
</head>
<body>
<h1>Sjakkbrett</h1>
<script>
var truefalse = true;
function changer(){
if(truefalse === true){
truefalse = false;
} else{
truefalse = true;
}
}
var svartbrikke = new Array();
svartbrikke [0] = "&#9820";
svartbrikke [1] = "&#9822";
svartbrikke [2] = "&#9821";
svartbrikke [3] = "&#9819";
svartbrikke [4] = "&#9818";
svartbrikke [5] = "&#9821";
svartbrikke [6] = "&#9822";
svartbrikke [7] = "&#9820";
svartbrikke [8] = "&#9823";
var hvitbrikke = new Array();
hvitbrikke [0] = "&#9814";
hvitbrikke [1] = "&#9816";
hvitbrikke [2] = "&#9815";
hvitbrikke [3] = "&#9813";
hvitbrikke [4] = "&#9812";
hvitbrikke [5] = "&#9815";
hvitbrikke [6] = "&#9816";
hvitbrikke [7] = "&#9814";
hvitbrikke [8] = "&#9817";
if(truefalse === true){
document.write('<table>');
for(var i = 0; i < 8; i++){
document.write('<tr align="center">');
for(var j = 0; j < 8; j++){
if(i === 0){
document.write('<td>' + svartbrikke[j] + '</td>');
}
if(i === 1){
document.write('<td>' + svartbrikke[8] + '</td>');
}
if(i === 6){
document.write('<td>' + hvitbrikke[8] + '</td>');
}
if(i === 7){
document.write('<td>' + hvitbrikke[7 - j] + '</td>');
}
else if(i >= 2 && i <= 5) {
document.write('<td> </td>');
}
}
document.write('</tr>');
}
document.write('</table>');
} else {
document.write('<table>');
for(var i = 0; i < 8; i++){
document.write('<tr align="center">');
for(var j = 0; j < 8; j++){
if(i === 0){
document.write('<td>' + hvitbrikke[j] + '</td>');
}
if(i === 1){
document.write('<td>' + hvitbrikke[8] + '</td>');
}
if(i === 6){
document.write('<td>' + svartbrikke[8] + '</td>');
}
if(i === 7){
document.write('<td>' + svartbrikke[7 - j] + '</td>');
}
else if(i >= 2 && i <= 5) {
document.write('<td> </td>');
}
}
document.write('</tr>');
}
document.write('</table>');
}
</script>
<button onclick="changer();"> Bytt side</button>
</body>
</html>
CSS:
root {
display: block;
}
table{
background-color: lightgray;
}
tr:nth-child(2n+1) > td:nth-child(2n){
content: center;
background-color: white;
box-sizing: border-box;
width: 40px;
height: 40px;
}
tr:nth-child(2n) > td:nth-child(2n+1){
content: center;
background-color: white;
box-sizing: border-box;
width: 40px;
height: 40px;
}

You cannot use document.write() after the page is rendered.
Use:
innerHTML
or
DOM methods
to change/add/remove page elements after the page is rendered.

You change the variable, but the code that checks it has already run and you don't rerun it.

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>

Having issue on loading elements to each container

I am trying to not load more than 9 alert on each .content but in result I am packing every number in group of 9 items and eliminating any items less than 10!
For example if the random value is 8 then nothing will shows in the content or if the random number is 19 only two set of content displays
How can I fix the following demo?
var itemsNumber = Math.floor(Math.random() * 50) + 1;
console.log(itemsNumber);
var contents = $('.contents');
var element = $('<div class="content"></div>');
for (var i = 0, j = 0; i < itemsNumber; i++, j++) {
element.append('<div class="alert alert-success" role="alert"> Alert ' + i + '</div>');
if (j == 9) {
contents.append(element);
element = $('<div class="content"></div>');
j = -1;
}
}
.content {
background: khaki;
margin: 10px;
border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents text-center">
</div>
The problem is that you condition to append the content is based on j == 9, so if you have less than 9 items it will never be true and never append. You can add || i === itemsNumber - 1 to tell if you are at the end of all the items.
var itemsNumber = 8; //Math.floor(Math.random() * 50) + 1;
console.log(itemsNumber);
var contents = $('.contents');
var element = $('<div class="content"></div>');
for (var i = 0, j = 0; i < itemsNumber; i++, j++) {
element.append('<div class="alert alert-success" role="alert"> Alert ' + i + '</div>');
if (j === 9 || i === itemsNumber - 1) {
contents.append(element);
element = $('<div class="content"></div>');
j = 0;
}
}
.content {
background: khaki;
margin: 10px;
border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents text-center">
</div>
Use condition i % 9 == 8 as break point
var itemsNumber = Math.floor(Math.random() * 50) + 1;
console.log(itemsNumber);
var contents = $('.contents');
var element = $('<div class="content"></div>');
for (var i = 0; i < itemsNumber; i++) {
element.append('<div class="alert alert-success" role="alert"> Alert ' + i + '</div>');
if (i % 9 == 8) {// break point
contents.append(element);
element = $('<div class="content"></div>');
}else if(i == itemsNumber - 1){// last loop
contents.append(element);
}
}
.content {
background: khaki;
margin: 10px;
border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents text-center">
</div>

The fifteen puzzle game

I am doing a fifteen puzzle game and I want that you only can click on a number next to the empty box, but now you can click everywhere...how to change this? I have thought that you can make an if- statement for columns and rows..
<!DOCTYPE html>
<html>
<head>
<title>The Fifteen Puzzle Game</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var currentBoard = new Array(' ','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
for(i=0 ; i++<100 ; x = Math.floor(Math.random()*16), y = Math.floor(Math.random()*16), currentBoard[x] = currentBoard.splice(y, 1, currentBoard[x])[0]);
repaint(); // Redraw puzzle board
//
// Funktion repaint()
// Redraw puzzle board
function repaint(){
currentString = "";
for(i=1;i<17;i++){
currentString += "<input type='button' id='" + i + "' value='" + currentBoard[i-1] + "' />";
if ( (i%4) == 0 ) currentString += "<br />";
}
$("#board").html(currentString);
}
function swapArrElems(index_a, index_b) {
var temp = currentBoard[index_a];
currentBoard[index_a] = currentBoard[index_b];
currentBoard[index_b] = temp;
}
$('#board').click(function(event){
current = $(event.target).attr("id")-1;
for(i=0;i<16;i++) if( currentBoard[i]==0 ) zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
});
});
</script>
<style>
input[type="button"] { width: 80px; height: 80px; font-size: 30px; }
</style>
</head>
<body>
<div id="board">
</div>
</body>
</html>
From the way I understood your code, you have 16 buttons id'ed by rows of 4. Each time a button is clicked, the array value of that button and the blank button swap. You're almost there. The detail that is the most important here is the button ID's, which stay the same throughout.
You need to add a comparison between the ID of the clicked button, and that of the blank button, which requires a conditional.
I'm not going to provide the code for you, because I don't want to just give away the answer. I'm going to give you the logic instead:
In your last function, after if( currentBoard[i]==0 ) zeroIndex = i;
**Else if** the id(clicked button) == id(blank button)-1. OR id(blank button)+1. OR
id(blank button)-4. OR id(blank button)+4 ........
Swap the elements.
Else
don't swap the elements.
Good luck! Hope this helps.
for (i = 0; i < 16; i++) {
if (currentBoard[i] == 0) {
if ((i - current) == 4 || (current - i) == 4 || (current - i) == 1 || (i - current) == 1) {
zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
}
}
}

How to use sort function and search function (regexp) together without strange errors?

In this prototype, I have "products" that are each individually stored in a div along with their price. I have added four buttons that sort the divs containing the products in alphabetical order (A-Z AND Z-A) as well as by price (lowest to highest and highest to lowest). These sorting functions work perfectly by themselves. I also have a search bar that acts as a search engine if you like an upon entering each character into the input field, will eliminate the products (div's) by name if they do not contain that letter(s). I have done this using a regular expression. This also worked by itself until I adapted it to try and work in conjunction with the sorting mechanisms.
Problem
I would like to be able to search for "products" using the search functionality to display the correct results regardless of what order the products have been sorted into.
Question
How is it possible to be able to display only the div's that contain the letter(s) searched for in the search bar regardless of the ordering (e.g. Z to A).
I think I ruined the search function itself by adding the index variable but you can't do list.name[i].match(res) can you? There is something wrong with the logic behind the search function. I believe the function that needs serious fixing is the searchProducts function.
The code AFTER I adapted the searchProducts function is below...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="resultsSpan"></div>
<div id="product0" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product1" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product2" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product3" style="height:60px; width:60px; background-color:blue;"></div>
<button onclick="sortprods()">
Sort A-Z
</button>
<button onclick="sortprods2()">
Sort Z-A
</button>
<button onclick="sortprods3()">
Price (low to high)
</button>
<button onclick="sortprods4()">
Price (high to low)
</button>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
</body>
</html>
<script>
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
list.sort(AtoZ);
for (var i = 0; i<list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
function AtoZ(a,b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
function ZtoA(a,b) {
if (a.name < b.name)
return 1;
if (a.name > b.name)
return -1;
return 0;
}
function LowtoHigh(a,b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function HightoLow(a,b) {
if (a.price < b.price)
return 1;
if (a.price > b.price)
return -1;
return 0;
}
function sortprods(){
list.sort(AtoZ);
currentSort = "AtoZ";
for (var i = 0; i < list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
}
function sortprods2(){
list.sort(ZtoA);
currentSort = "ZtoA";
for (var j = 0; j < list.length; j++) {
document.getElementById("product" + j).innerHTML = list[j].name + ", " + list[j].price;
}
}
function sortprods3(){
currentSort = "LowtoHigh";
list.sort(LowtoHigh);
for (var k = 0; k < list.length; k++) {
document.getElementById("product" + k).innerHTML = list[k].name + ", " + list[k].price;
}
}
function sortprods4(){
currentSort = "HightoLow";
list.sort(HightoLow);
for (var l = 0; l < list.length; l++) {
document.getElementById("product" + l).innerHTML = list[l].name + ", " + list[l].price;
}
}
var input = "";
var index = [];
var currentSort = "AtoZ";
function searchProducts(){
input = document.getElementById("searchbar").value;
if(input == ""){
document.getElementById("product0").style.display = "block";
document.getElementById("product1").style.display = "block";
document.getElementById("product2").style.display = "block";
document.getElementById("product3").style.display = "block";
}else{
switch(currentSort){
case "AtoZ":
list.sort(AtoZ);
for(var a = 0; a < list.length; a++){
document.getElementById("product" + a).innerHTML = list[a].name + ", " + list[a].price;
index.push(list[a].name);
}
index.sort();
break;
case "ZtoA":
list.sort(ZtoA);
for(var b = 0; b < list.length; b++){
document.getElementById("product" + b).innerHTML = list[b].name + ", " + list[b].price;
index.push(list[b].name);
}
index.sort();
index.reverse();
break;
case "LowtoHigh":
list.sort(LowtoHigh);
for(var c = 0; c < list.length; c++){
index.push(list[c].price);
}
index.sort(function(a, b){return a-b});
break;
case "HightoLow":
list.sort(HightoLow);
for(var d = 0; d < list.length; d++){
index.push(list[d].price);
}
index.sort(function(a, b){return b-a});
break;
}
test = input;
re = new RegExp(test, 'gi');
for(var e=0; e<index.length; e++){
if(index[e].match(re)){
document.getElementById("product"+e).style.display = "block";
}else{
document.getElementById("product"+e).style.display = "none";
}
}
}
}
</script>
The code before I adapted the searchProducts function (THAT WORKED PERFECTLY BEFORE ADAPTION) is...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
<div id="demo"></div>
<div id="demo2">
<div id="product1" style="background-color:red; height:100px; width:100px; float:left">chocolate<br /><button onClick="grow()" id="button1">Show Info</button></div>
<div id="product2" style="background-color:blue; height:100px; width:100px; float:left">Mint</div>
<div id="product3" style="background-color:green; height:100px; width:100px; float:left">Caramel</div>
</div>
</body>
</html>
<script>
var index = ["Chocolate", "Mint", "Caramel"];
var input = "";
var currentLog = [];
function searchProducts(){
currentLog = [];
input = document.getElementById("searchbar").value;
/*function searchStringInArray(str, strArray){
for (var j = 0; j < strArray.length; j++) {
if (strArray[j].match(str)){
var temp = strArray.slice(j, (j + 1));
currentLog.push(temp);
console.log(j);
}
}
document.getElementById("demo").innerHTML = currentLog.join("<br />");
if(currentLog.length < 1){
document.getElementById("demo").innerHTML = "No results were found.";
}
}*/
test = input;
re = new RegExp(test, 'gi');
/*if(!index[0].match(re)){
document.getElementById("product1").style.display = "none";
}
if(!index[1].match(re)){
document.getElementById("product2").style.display = "none";
}
if(!index[2].match(re)){
document.getElementById("product3").style.display = "none";
}*/
for(var e=0; e<index.length; e++){
if(!index[e].match(re)){
document.getElementById("product"+(e+1)).style.display = "none";
}else{
document.getElementById("product"+(e+1)).style.display = "block";
}
}
if(document.getElementById("product1").style.display == "none" && document.getElementById("product2").style.display == "none" && document.getElementById("product3").style.display == "none"){
document.getElementById("demo").innerHTML = "no results";
}else{
document.getElementById("demo").innerHTML = "";
}
/*searchStringInArray(input, index);*/
}
function grow(){
if(document.getElementById('product1').style.height == "200px"){
document.getElementById('product1').style.height = '100px';
document.getElementById('button1').innerHTML = "Show Info";
}else{
document.getElementById('product1').style.height = "200px";
document.getElementById('button1').innerHTML = "Hide Info";
}
}
</script>
The issue is that when you sort your list when a filter was applied earlier, you only move the data, not the visibility of the containers of those data.
Instead you could re-execute the regex matching, every time you display the content according to the current sort order. That way you are sure the right data are visible at all times.
You have a lot of duplication in your code, with several places where you have the same loop, or code that only differs in one aspect. You should always try to "Don't Repeat Yourself" (DRY).
I would suggest to have one function for displaying content only. You could pass it the sort function to apply. Note that this means the HTML also changes where you have specified the event handlers. There are many other such simplifications, which are too many to mention all.
Check this snippet:
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
var currentRegex = /./; // any character matches
var currentSort = AtoZ;
// Call the function we have for applying the initial sort order and filter
searchProducts(document.getElementById('searchbar').value);
// Shorter ways to compare:
function AtoZ(a,b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }
function ZtoA(a,b) { return AtoZ(b,a) }
function LowtoHigh(a,b) { return a.price - b.price }
function HightoLow(a,b) { return b.price - a.price }
// One function for all sort orders: pass sort order as function
function sortprods(sorter) {
var showCount = 0;
currentSort = sorter;
list.sort(currentSort);
for (var i = 0; i < list.length; i++) {
var product = document.getElementById("product" + i);
// use textContent, not innerHTML
product.textContent = list[i].name + ", " + list[i].price;
var show = !!list[i].name.match(currentRegex);
product.style.display = show ? "" : "none";
showCount += show;
}
document.getElementById('resultsSpan').textContent =
showCount ? '' : 'no results';
}
function searchProducts(input){
// Argument is value of input
// No need to `switch` on currentSort. Can do this with generic code.
// Deal with empty input by using all-matching `.` regexp.
// `g` not needed.
currentRegex = new RegExp(input.length ? input : '.', 'i');
sortprods(currentSort);
}
<div id="resultsSpan"></div>
<div id="product0" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product1" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product2" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product3" style="height:45px; width:60px; background-color:lightblue;"></div>
<button onclick="sortprods(AtoZ)">Sort A-Z</button>
<button onclick="sortprods(ZtoA)">Sort Z-A</button>
<button onclick="sortprods(LowtoHigh)">Price (low to high)</button>
<button onclick="sortprods(HightoLow)">Price (high to low)</button>
<input type="text" id="searchbar" onkeyup="searchProducts(this.value)"/>
About the ternary operator:
You asked in comments about the ternary operator:
product.style.display = list[i].name.match(currentRegex) ? "" : "none";
The above is equivalent to this:
var temp;
if (list[i].name.match(currentRegex)) {
temp = "";
} else {
temp = "none";
}
product.style.display = temp;
... except that no temp variable is created of course.
The other occurrence:
currentRegex = new RegExp(input.length ? input : '.', 'i');
... is equivalent to:
var temp;
if (input.length) { // if length is defined and not 0
temp = input;
} else {
temp = ".";
}
currentRegex = new RegExp(temp, 'i');

In an array, how can I get values printed the way I would like them printed instead of the last value?

I am using a for-loop to get the values of a sorted list using .html() but it is only printing the last value in the array. I thought by using myArray.length and myArray[i] in the loop that it would cycle through as expected.
Ideally, I would like this to read:
The sorted values are:
1, 2, 3, 4, 5 etc. . .
What am I doing wrong?
Fiddle here.
HTML:
<div id="wrapper">
<div id="content">
<h1>Let's Do Some Math</h1>
<div id="intake">
<input type="text" id="input"> <button id="inTakeButton">Push to Array</button> <button id="showArray">Show Array</button> <button id="doMath">Do Math</button>
</div>
<div id="middle">
<ul id="list">
</ul>
</div>
<div id="output">
<p id="sorted"></p>
<p id="sum"></p>
<p id="average"></p>
</div>
</div>
</div>
CSS:
#wrapper{
width: 80%;
margin: 0 auto;
border: 1px solid black;
border-radius: 5px 5px 5px 5px;
box-shadow: 5px 5px 10px 3px black;
padding: 10px;
}
h1 {
text-align: center;
color: orange;
text-shadow: 1px 1px blue;
}
#intake {
text-align: center;
}
JavaScript:
myArray = [];
var theTotal;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " + theTotal);
var average = (theTotal/myArray.length);
$('#average').html("");
$('#average').html("The mean value is: " + average);
var sorted = myArray.sort();
$('#sorted').html("");
for (var i = 0; i < myArray.length; i++) {
$('#sorted').html("The sorted values are: <br>" + myArray[i] + ", ");
};
});
});
});
You don't even need to use loop trough the array to do this, just:
$('#sorted').html("The sorted values are: <br>" + myArray.join(", "));
In your loop for the sorted values, you are overriding the entire HTML content each time.
Try something like
for (var i = 0; i < myArray.length; i++) {
$('#sorted').append(myArray[i] + ", ");
};
You can try this. Instead of showing the values using a loop, you can just display the whole array at once. Edited JS code:
myArray = [];
var theTotal;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " + theTotal);
var average = (theTotal/myArray.length);
$('#average').html("");
$('#average').html("The mean value is: " + average);
var sorted = myArray.sort();
$('#sorted').html("The sorted values are: <br>" + myArray )
});
});
});
Check out the fiddle
var sorted = myArray.sort(function (a, b) {
return a - b;
});
use this for sorting

Categories

Resources