I've been trying many different methods and rewriting my code to achieve something that I feel is quite simple but I can't seem to get it.
I have two increment/decrement buttons but I want to disable the click function on the subtract button when the value reaches 0 as to not input negative numbers.
Currently on my jsfiddle I have the calculator working, however when I try to disable the subtract button when the value is 0, it disables the button completely, even when the value is no longer 0. It seems jQuery is not checking to see if the value has changed.
Any ideas on how can I fix this? Thanks!
Example here:
https://jsfiddle.net/jony000/frupofqe/22/
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
JQuery
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function() {
showers++;
rate.html(showers);
})
minus.click(function() {
showers--;
rate.html(showers);
})
/*if (showers == 0) {
minus.css("pointer-events","none");
} else{
minus.css("pointer-events", "auto");
}*/
You have to check if shower is zero inside the click event listener for the minus element:
minus.click(function() {
rate.html(--showers);
if (showers === 0) {
minus.css("pointer-events", "none");
} else{
minus.css("pointer-events", "auto");
}
});
Check for 0 before you decrement. I believe its more clearly readable to just not decrement it rather than disabling the control, unless you had other logic thats not shown in the demo.
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function(){
showers++;
rate.html(showers);
})
minus.click(function(){
if (showers <= 0)
return;
showers--;
rate.html(showers);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
you just need to move your entire if block at the bottom inside of your functions... or better yet, create a new function and call that one inside the others. Here's an example
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
//This is new
var checkForZero = function() {
if (showers == 0) {
minus.css("pointer-events","none");
} else {
minus.css("pointer-events", "auto");
}
};
plus.click(function(){
showers++;
rate.html(showers);
checkForZero(); //call new function
})
minus.click(function(){
showers--;
rate.html(showers);
checkForZero(); //call new function
})
you can do something like this.
var rateMinus = $(".rate-minus");
var value = 0;
updateRateMinus(); // update on initial load
$(".rate-plus").click(function() {
parseInt($(".shower-rate").text(value + 1));
value = value + 1;
updateRateMinus();
});
$(".rate-minus").click(function() {
parseInt($(".shower-rate").text(value - 1));
value = value - 1;
updateRateMinus();
});
function updateRateMinus() {
if ($(".shower-rate").text() == 0) {
rateMinus.css('pointer-events', 'none');
} else {
rateMinus.css("pointer-events", "auto");
}
}
You could just set up an call that would check a given condition (if your value is 0) and use that to toggle if your subtract button was enabled or disabled via a ternary operation :
minus.css("pointer-events",showers === 0 ? "none" : "auto");
Then you could simply check for that scenario when either of your events occur :
plus.click(function(){
showers++;
UpdateRate();
})
minus.click(function(){
showers--;
UpdateRate();
})
function UpdateRate() {
// This will disable your button if showers is 0
minus.css("pointer-events",showers === 0 ? "none" : "auto");
rate.html(showers);
}
Example
var rateMinus = $(".rate-minus");
var ratePlus = $(".rate-plus");
var rate = $(".shower-rate");
var value = 0;
ratePlus.click(function() {
value++;
UpdateRate();
})
rateMinus.click(function() {
value--;
UpdateRate();
})
function UpdateRate() {
debugger;
// This will disable your button if showers is 0
rateMinus.css("pointer-events", value === 0 ? "none" : "auto");
rate.html(value);
}
table {
margin: auto;
color: #cecece;
}
.shower td {
padding: 10px;
}
.rate-minus,
.rate-plus,
.period-minus,
.period-plus {
width: 50px;
height: 50px;
background: #a8d6ff;
border-radius: 100%;
text-align: center;
font-size: 24px;
color: black;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How often do you shower?
<table class="shower">
<tbody>
<tr>
<td class="rate-minus" id="test">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a
</p>
<table class="shower">
<tbody>
<tr>
<td class="period-minus">
-
</td>
<td class="shower-period">
Day
</td>
<td class="period-plus">
+
</td>
</tr>
</tbody>
</table>
Related
I have a table where the text in column on the left can be clicked and the text in the column on the right will change accordingly. The way it should work is when one of the options on the left is clicked, only the text on the right that corresponds to the selected option appears. However, when I click one of my options on the left it just hides all of the text on the right and does not display the part I want to see.
var selectColor = function( element ) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName( "prot_id" );
for ( i = 0; i < prots.length; ++i ) {
prots.item(i).style.color = 'black';
element.style.color = 'red';
}
}
var selectProtein = function( element ) {
/* Change what info is displayed based on current selection */
var proteinInfo = document.getElementsByClassName( "prot_func" ) ;
for( j = 0; j < proteinInfo.length; ++j ) {
proteinInfo[j].style['display'] = 'none' ;
}
var proteinIDs = ["gria1", "gria2", "gria3", "gria4"] ;
proteinIDs.forEach(function(entry) {
if( element.src.includes(entry)) {
var theProtein = document.getElementById(entry) ;
theProtein.style['display'] = 'block' ;
}
})
}
<head>
<link rel='stylesheet' type='text/css' href='./index.css'>
</head>
<body>
<table>
<tr>
<td>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA1_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA2_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA3_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA4_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">...</p>
<p id="gria2" class="prot_func">...</p>
<p id="gria3" class="prot_func">...</p>
<p id="gria4" class="prot_func">...</p>
</td>
</tr>
</table>
</body>
There are a few issues that you are having so I updated your code.
I got rid of onclick and went with an event handler instead.
I got rid of the protein array loop and just added each id as a data attribute to the paragraph tags.
Instead of hiding/showing based on the style, I just add/remove a class instead.
var selectColor = function(element) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName("prot_id");
for (i = 0; i < prots.length; ++i) {
prots.item(i).classList.remove("active");
}
element.classList.add("active")
}
var selectProtein = function(element) {
var proteinInfo = document.getElementsByClassName("prot_func");
for (j = 0; j < proteinInfo.length; ++j) {
proteinInfo[j].classList.remove("active");
}
theProtein = document.querySelector("#" + element.dataset.id);
theProtein.classList.add("active");
}
document.querySelectorAll(".prot_id").forEach(function(el) {
el.addEventListener("click", function(e) {
selectColor(e.target);
selectProtein(e.target)
});
});
.prot_func {
display: none;
}
.prot_func.active {
display: block;
}
.prot_id.active {
color: red;
}
<table>
<tr>
<td>
<p class="prot_id" data-id="gria1">GRIA1_HUMAN</p>
<p class="prot_id" data-id="gria2">GRIA2_HUMAN</p>
<p class="prot_id" data-id="gria3">GRIA3_HUMAN</p>
<p class="prot_id" data-id="gria4">GRIA4_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">.1..</p>
<p id="gria2" class="prot_func">.2..</p>
<p id="gria3" class="prot_func">.3..</p>
<p id="gria4" class="prot_func">..4.</p>
</td>
</tr>
</table>
From your snippet, you are going to show the options on the right side based on the selected p tag content.
So if GRIA1_HUMAN is selected, gria1 should be shown.
You can get the value of p content using innerText attribute and compare the values using it. I have attached the working example.
var selectColor = function (element) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName("prot_id");
for ( i = 0; i < prots.length; ++i ) {
prots.item(i).style.color = 'black';
}
element.style.color = 'red';
}
var selectProtein = function (element) {
/* Change what info is displayed based on current selection */
var proteinInfo = document.getElementsByClassName("prot_func") ;
for( j = 0; j < proteinInfo.length; ++j) {
proteinInfo[j].style['display'] = 'none' ;
}
var proteinIDs = ["gria1", "gria2", "gria3", "gria4"] ;
const elementText = element.innerText.toLowerCase();
proteinIDs.forEach(function(entry) {
if(elementText.includes(entry)) {
var theProtein = document.getElementById(entry);
theProtein.style['display'] = 'block';
}
});
}
<table border="1">
<tr>
<td>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA1_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">...</p>
</td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA2_HUMAN</p></td>
<td><p id="gria2" class="prot_func">...</p></td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA3_HUMAN</p></td>
<td><p id="gria3" class="prot_func">...</p></td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA4_HUMAN</p></td>
<td><p id="gria4" class="prot_func">...</p></td>
</tr>
</table>
I have the following html:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
<td id=col4">7</td>
</tr>
</tbody>
</table>
I would like to use JQuery to append everything after column 3 (col3) to a new row. Ideally I would end up with something like this:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
</tr>
<tr>
<td id=col4">7</td>
</tr>
</tbody>
</table>
Any ideas how this could be achieved? I have tried a few things but haven't been able to get it working.
You could define a generic redistribution function, that takes as argument the desired number of columns, and which just fills up the rows with content from top to bottom, using that number of columns.
It could even be a jQuery plugin:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; border: 2px solid }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
Here is a version with one extra statement that sets the colspan on the very last td element so it occupies the remaining columns in the last row:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
$("td", this).last().attr("colspan", rowCount * maxNumCols - cells.length + 1);
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
It sounds like you're still new to jQuery. To give you an idea how to solve your described problem, I have written a solution here. I hope it helps you.
// parameters for splitting
var splitIndex = 3,
splitClass = '.split-columns';
// start the splitting
splitColumnsIntoRows();
function splitColumnsIntoRows() {
var $tables = $(splitClass),
numberTables = $tables.length;
if (numberTables == 0) {
return;
}
for (var i = 0; i < numberTables; i++) {
iterateSplittingRows($($tables[i]).find('tr'));
}
}
function iterateSplittingRows($currentRows) {
var $currentRow,
numberRows = $currentRows.length;
if (numberRows == 0) {
return;
}
for (var i = 0; i < numberRows; i++) {
$currentRow = $($currentRows[i]);
iterateSplittingFields($currentRow, $currentRow.find('th, td'));
}
}
function iterateSplittingFields($currentRow, $currentFields) {
var $newRow,
newRows = [],
childrenLength,
numberFields = $currentFields.length;
if (numberFields == 0) {
return;
}
for (var i = 0; i < numberFields; i++) {
if (i < splitIndex) {
continue;
}
if (i % splitIndex == 0) {
$newRow = $('<tr></tr>');
}
$newRow.append($currentFields[i]);
if (i == numberFields - 1) {
childrenLength = $newRow.children().length;
// fill the row with empty fields if the length does not fit the splitIndex
for (var j = splitIndex; j > childrenLength; j--) {
$newRow.append($('<td></td>'));
}
}
if (
(i >= splitIndex && i % splitIndex == splitIndex - 1)
||
i == numberFields - 1
){
newRows.push($newRow);
}
}
$currentRow.after(newRows);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="split-columns">
<tbody>
<tr>
<td class="col_01">01</td>
<td class="col_02">02</td>
<td class="col_03">03</td>
<td class="col_04">04</td>
<td class="col_05">05</td>
<td class="col_06">06</td>
<td class="col_07">07</td>
<td class="col_08">08</td>
<td class="col_09">09</td>
</tr>
<tr>
<td class="col_10">10</td>
<td class="col_11">11</td>
<td class="col_12">12</td>
<td class="col_13">13</td>
<td class="col_14">14</td>
<td class="col_15">15</td>
<td class="col_16">16</td>
<td class="col_17">17</td>
</tr>
<tr>
<td class="col_19">19</td>
<td class="col_20">20</td>
<td class="col_21">21</td>
<td class="col_22">22</td>
<td class="col_23">23</td>
<td class="col_24">24</td>
<td class="col_25">25</td>
</tr>
</tbody>
</table>
Can you help me with this problem? I can't use return x value for my other function. I want when I click on some element, then script load ID of clicked element and then change color of element with this ID.
Is there some better solution for my problem? (in pure JS, not in Jquery)
Thanks.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
<script>
document.addEventListener('click', function(e) {
x=e.target.id;
return x
});
document.getElementById(x).onclick =
function(x) {
if (document.getElementById(x).style.backgroundColor !== 'yellow') {
document.getElementById(x).style.backgroundColor = 'yellow';
}
else {
document.getElementById(x).style.backgroundColor = 'red';
}
};
</script>
Change your code to below.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
document.addEventListener('click', function(e) {
x=e.target.id;
function() {
var bgColor = document.getElementById(x).style.backgroundColor;
if (bgColor !== 'yellow') {
bgColor = 'yellow';
}
else {
bgColor = 'red';
}
}
});
</script>
Ok i find solution on my problem.
The solution was put all my script in one function and than evrything work.
I learning JS about 1 mount and now I have made one simple LIGHTS OFF game.
Now I nedd some function that check all cells color and alert end of game, but i cant answer a new question because by question is not voted well, and i dont know why.
Here is the example of my code:
document.addEventListener('click', function(e) {
var x = e.target.id
var up = ((Math.floor(x.charAt(0))-1).toString()).concat(x.charAt(1));
var down = ((Math.floor(x.charAt(0))+1).toString()).concat(x.charAt(1));
var left = (x.charAt(0)).concat((Math.floor(x.charAt(1))-1).toString());
var right = (x.charAt(0)).concat((Math.floor(x.charAt(1))+1).toString());
if( document.getElementById(x).style.backgroundColor == ''){document.getElementById(x).style.backgroundColor = 'black';}
else{document.getElementById(x).style.backgroundColor ='';}
if(document.getElementById(up)!=null){
if( document.getElementById(up).style.backgroundColor == ''){document.getElementById(up).style.backgroundColor = 'black';}
else{document.getElementById(up).style.backgroundColor ='';}}
if(document.getElementById(down)!=null){
if( document.getElementById(down).style.backgroundColor == ''){document.getElementById(down).style.backgroundColor = 'black';}
else{document.getElementById(down).style.backgroundColor ='';}}
if(document.getElementById(left)!=null){
if( document.getElementById(left).style.backgroundColor == ''){document.getElementById(left).style.backgroundColor = 'black';}
else{document.getElementById(left).style.backgroundColor ='';}}
if(document.getElementById(right)!=null){
if( document.getElementById(right).style.backgroundColor == ''){document.getElementById(right).style.backgroundColor = 'black';}
else{document.getElementById(right).style.backgroundColor ='';}}
// var all = document.getElementsByTagName("TD");
// var i;
// for (i = 0; i < all.length; i++) {
// all[i].style.backgroundColor!=='yellow';
// alert('a')
// break}
})
td {
padding: 50px;
background-color: yellow;
<table>
<tr>
<td id='11'></td>
<td id='12'></td>
<td id='13'></td>
<td id='14'></td>
<td id='15'></td>
</tr>
<tr>
<td id='21'></td>
<td id='22'></td>
<td id='23'></td>
<td id='24'></td>
<td id='25'></td>
</tr>
<tr>
<td id='31'></td>
<td id='32'></td>
<td id='33'></td>
<td id='34'></td>
<td id='35'></td>
</tr>
<tr>
<td id='41'></td>
<td id='42'></td>
<td id='43'></td>
<td id='44'></td>
<td id='45'></td>
</tr>
<tr>
<td id='51'></td>
<td id='52'></td>
<td id='53'></td>
<td id='54'></td>
<td id='55'></td>
</tr>
</table>
I'm trying to find a way to calculate the data that was entered into an array.
The JavaScript
function getInput()
{
var even = [];
var odd = [];
var num = prompt("Enter your number");
if (num % 2 === 0) {
alert("Data entered into array.");
even.push(num);
}
else if (num % 2 == 1) {
alert("Data entered into array.");
odd.push(num)
}
else {
alert("Invalid input.");
}
}
function finished() //This is where the calculations are done. It's accessed by a button in my HTML.
{
var sum = document.getElementById("leftSumOutput").innerHTML = even[];
}
This is the structure for the page. I'm trying to use tables to store the outputs.
The HTML
<!DOCTYPE html>
<html>
<head>
<title>Sample Title</title>
<script type="text/javascript" src="assignmentOne.js"></script>
<link rel="stylesheet" type="text/css" href="assignmentOne.css">
<link rel="icon" href="favicon.png" type="image/x-icon" />
</head>
<body>
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input" onclick="getInput()"><b>Click to input data</b></button><br><br>
<button id="done" onclick="finished()">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="leftSumOutput"></td>
<td id="rightSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="leftAvgOutput"></td>
<td id="rightAvgOutput"></td>
</tr>
</table>
</div>
</body>
</html>
I want to calculate the items within the array. I'm a novice, so I apologize in advance.
EDIT: I forgot to mention that I don't know how to calculate the averages of the fields either. Any help with that would be appreciated. Thanks everyone for your assistance so far!
I think you are little bit confused with scoping of variables.
Here is an example of how it could've been done:
(function(w, d) {
var odds = [], evens = [], button, elSumOdds,elSumEvens, elAvgOdds, elAvgEvens, s
w.addEventListener('load', function() {
button = d.querySelector('button')
elSumOdds = d.querySelector('#sum-odds')
elSumEvens = d.querySelector('#sum-evens')
elAvgOdds = d.querySelector('#avg-odds')
elAvgEvens = d.querySelector('#avg-evens')
button.addEventListener('click', calculate)
})
function calculate() {
var i = prompt('enter number') | 0;
if ((i|0)%2) {
odds.push(i)
s = odds.reduce(function(a,n) { return a+n }, 0)
elSumOdds.innerText = s
elAvgOdds.innerText = s / odds.length
} else {
evens.push(i)
s = evens.reduce(function(a,n) { return a+n }, 0)
elSumEvens.innerText = s
elAvgEvens.innerText = s / evens.length
}
}
})(window, document)
<button > calculate</button>
<table>
<tr><td></td><td>Sum</td><td>Avg</td></tr>
<tr><td>Odds</td><td id='sum-odds'></td><td id='avg-odds'></td></tr>
<tr><td>Evens</td><td id='sum-evens'></td><td id='avg-evens'></td></tr>
</table>
If you need to calculate sum of each element in array you need to write map function. Visit link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
if you just need to know amount of elements, call: alert(even.length);
Note: #vittore 's structure inspired this change.
(function(d) {
d.getElementById('input').addEventListener('click', getInput);
d.getElementById('done').addEventListener('click', finished);
var elSumOdd = d.getElementById('oddSumOutput');
var elSumEven = d.getElementById('evenSumOutput');
var elAvgOdd = d.getElementById('oddAvgOutput');
var elAvgEven = d.getElementById('evenAvgOutput');
var even = [];
var odd = [];
function getInput() {
var num = prompt("Enter your number") | 0;
if (num % 2 == 0) {
even.push(num);
} else if (num % 2 == 1) {
odd.push(num);
} else {
alert("Invalid input.");
}
finished();
}
function finished() { //This is where the calculations are done. It's accessed by a button in my HTML.
elSumOdd.innerHTML = odd.reduce(function(a, b) {
return a + b;
}, 0);
elSumEven.innerHTML = even.reduce(function(a, b) {
return a + b;
}, 0);
elAvgOdd.innerHTML = elSumOdd.innerHTML / odd.length || 0;
elAvgEven.innerHTML = elSumEven.innerHTML / even.length || 0;
}
})(document);
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input"><b>Click to input data</b>
</button>
<br>
<br>
<button id="done">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="evenSumOutput"></td>
<td id="oddSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="evenAvgOutput"></td>
<td id="oddAvgOutput"></td>
</tr>
</table>
</div>
First I would like to say thank you to the individuals that helped me with this question before. For the ones that decided to close my post without even trying to first assist me, please refrain from closing my post if you are not deciding to help and calling my issue too broad. Also, I'm not looking as of this time to "optimize" my code or for corrections with how I expatiate my summary below. Now, for the real issue...
I'm trying my hand at building a tic-tac-toe game with plain vanilla Javascript, so I'm hoping we can stay in the boundaries of keeping it simple Javascript. Do not optimize code!
What I require is the following: I need code that will check each square to see if it's filled with an X or an O. If squares are still available, no need for an alert but if all squares are filled, I need it to alert me "No more moves!"
I have started the function checkEmpty
Thank you for your assistance and time!
Here is the code I have got so far:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tic Tac Toe</title>
<style>
td {
border: 1px solid black;
height: 250px;
width: 250px;
font-family: sans-serif;
font-size: 150pt;
text-transform: uppercase;
}
</style>
</head>
<body>
<table>
<tr>
<td align="center" id="square1" onclick="displayMarker('square1');"></td>
<td align="center" id="square2" onclick="displayMarker('square2');"></td>
<td align="center" id="square3" onclick="displayMarker('square3');"></td>
</tr>
<tr>
<td align="center" id="square4" onclick="displayMarker('square4');"></td>
<td align="center" id="square5" onclick="displayMarker('square5');"></td>
<td align="center" id="square6" onclick="displayMarker('square6');"></td>
</tr>
<tr>
<td align="center" id="square7" onclick="displayMarker('square7');"></td>
<td align="center" id="square8" onclick="displayMarker('square8');"></td>
<td align="center" id="square9" onclick="displayMarker('square9');"></td>
</tr>
</table>
<script>
var cp1 = 1;
function displayMarker(allSquares) {
if (document.getElementById(allSquares).innerHTML != "") {
alert("Choose another square");
}
else {
if (cp1 == 1) {
document.getElementById(allSquares).innerHTML = "X";
cp1 = 2;
}
else {
document.getElementById(allSquares).innerHTML = "O";
cp1 = 1;
}
}
checkEmpty();
}
function checkEmpty() {
for (var i = 1; i <= 9; i++) {
console.log(document.getElementById('square' + i).innerHTML + " square" + i);
}
</script>
</body>
</html>
Should work:
function checkEmpty() {
for (var i = 1; i <= 9; i++) {
if (!document.getElementById('square' + i).innerHTML) return;
}
alert("all squares filled");
}
function checkEmpty() {
var isEmpty = false;
for (var i = 1; i <= 9; i++) {
var squareVal = document.getElementById('square' + i).innerHTML;
if(squareVal.length == 0)
{
isEmpty = true;
break;
}
}
if(!isEmpty)
{
alert('No more moves');
}
}