How to make sure that only one decimal seperator is added? - javascript

What I made over here is a calculator with two display , some operators and number buttons, obviously in HTML.
But , I cannot figure out how to implement the decimal seperator.
At first , I thought that I could use maybe a variable as a boolean switch , but turns out , the number() function destroys the . decimal seperator before I can reset it to true.
Below is a sample of the html as well as the GUI.
I was thinking of making a new variable called var isExist, which can scan if the decimal still exists or not and then work out.
But anyways , code is given below.
Did not use JSFiddle , because , it seems that similar services don't work in my region
enter image description here
<html>
<head>
<link rel="stylesheet" href="css/index.css">
<style type="text/css">
#font-face{
font-family: josefin-sans light;
src: url(font/static/JosefinSans-Light.ttf);
}
</style>
</head>
<body>
<div id="mySidenav" class="sidenav">
×
About
Services
Clients
Contact
</div>
<div id="swipe-area"></div>
<span id= "menu" onclick="openNav()"> ☰</span>
<span id="title">Calculator</span>
<div id="calc">
<table>
<tr rowspan="2" id="display">
<th colspan="4">
<p id="prev"></p>
<p id="curr"></p>
</th>
</tr>
<tr class="keyboard">
<th><input type="button" class="operator" id="clear" value="C"></th>
<th><input type="button" class="operator" id="backspace" value=←></th>
<th><input type="button" class="operator" id="invert" value=±></th>
<th><input type="button" class="operator" id="/" value=&div;></th>
</tr>
<tr class="keyboard">
<th><input type="button" class="number" id="7" value="7"></th>
<th><input type="button" class="number" id="8" value="8"></th>
<th><input type="button" class="number" id="9" value="9"></th>
<th><input type="button" class="operator" id="*" value=×></th>
</tr>
<tr class="keyboard">
<th><input type="button" class="number" id="4" value="4"></th>
<th><input type="button" class="number" id="5" value="5"></th>
<th><input type="button" class="number" id="6" value="6"></th>
<th><input type="button" class="operator" id="-" value=−></th>
</tr>
<tr class="keyboard">
<th><input type="button" class="number" id="1" value="1"></th>
<th><input type="button" class="number" id="2" value="2"></th>
<th><input type="button" class="number" id="3" value="3"></th>
<th><input type="button" class="operator" id="+" value=&plus;></th>
</tr>
<tr class="keyboard">
<th></th>
<th><input type="button" class="number" id="0" value="0"></th>
<th><input type="button" class="operator" id="." value=&dot;></th>
<th><input type="button" class="operator" id="=" value=&equals;></th>
</tr>
</table>
</div>
</body>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/jQuery.js"></script>
<script type="text/javascript" src="js/jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="js/swipe.js"></script>
</html>
function openNav(){//ignore this
document.getElementById("mySidenav").style.width ="100%";
}
function closeNav(){//ignore this too
document.getElementById("mySidenav").style.width ="0px";
}
function getPrevious(){//gets the value for top display
return document.getElementById("prev").innerText;
}
function setPrevious(num){//sets the value for top display
document.getElementById("prev").innerText=num;
}
function getCurrent(){//gets the value for bottom display
return document.getElementById("curr").innerText;
}
function setCurrent(num){//sets the value for bottom display
if(num==""){
document.getElementById("curr").innerText=num;
}
else{
document.getElementById("curr").innerText=getFormattedNumber(num)+symbol;
symbol="";
}
}
function getFormattedNumber(num){//formats number into indian numeral system
var n = Number(num);
var value = n.toLocaleString("hi-IN");
return value;
}
function reverseNumber(num){//extract number from here
return Number(num.replace(/,/g,''));
}
//catch operation of operator from here
var operator = document.getElementsByClassName("operator");
var rep=true;//---->this is the switch to enable decimal button(not functional)
var del;
for(var i=0;i<operator.length;i++){
operator[i].addEventListener("click",function(){
if(this.id=="clear"){
setPrevious("");
setCurrent("");
}
else
if(this.id=="backspace"){
var output=reverseNumber(getCurrent()).toString();
if(output){
del=output.charAt(output.length-1);//I am sure the code went wrong here
if(del=="."){
rep=true;
}
output=output.substr(0,output.length-1);
setCurrent(output);
}
}
else
if(this.id=="invert"){
var output=reverseNumber(getCurrent());
if(output!=""){
output=-output;
setCurrent(output);
}
}
else
if(this.id=="."){//this is probably WHERE YOU WANT TO CHECK
var output=reverseNumber(getCurrent()).toString();
if(output!=""){
if(rep==true){
symbol=this.id;
output=output
setCurrent(output);
rep=false;
}
}
}
else{
var current=getCurrent();
var previous=getPrevious();
if(output=="" && history!=""){
if(isNaN(history[history.length-1])){
history=history.substr(0,history.length-1);
}
}
//code is incomplete here , ignore it
}
})
}
var number = document.getElementsByClassName("number");
for(var i=0;i<number.length;i++){
number[i].addEventListener("click",function(){
var output=reverseNumber(getCurrent());
if(output!=NaN){
if(getCurrent().charAt(getCurrent().length-1)=="."){
output=output+(0.1*this.id)
setCurrent(output);
}
else{
output=output+this.id;
setCurrent(output);
}
}
})
}
body{
margin: 0px;
background: linear-gradient(to left top,rgb(99, 99, 255),rgb(126, 197, 255));
font-family: josefin-sans light;
}
.sidenav{
height: 100%;
width: 0%;
position:fixed;
z-index: 1;
top:0;
left: 0;
background-color: rgb(255, 255, 255);
overflow-x: hidden;
padding-top: 60px;
transition: 0.5s;
}
.sidenav a{
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: rgb(132, 132, 255);
display: block;
transition: 0.3s;
}
.sidenav a:hover{
color: #000000;
font-size: 230%;
}
.sidenav .closebtn{
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
.sidenav .closebtn:hover{
color: red;
}
#menu,#title{
font-size: 250%;
color: white;
}
#title{
position: absolute;
left: 50%;
top: 3%;
z-index: 0;
transform: translate(-50%,-50%);
}
#main{
transition: margin-left .5s;
padding: 20px;
}
#media screen and (max-height:450px){
.sidenav{ padding-top: 15px;}
.sidenav a{font-size: 18px;}
}
::-webkit-scrollbar{
height: 5px;
}
::-webkit-scrollbar-thumb{
background: rgb(223, 223, 223);
border-radius: 10px;
}
table{
margin: auto;
text-align: center;
border-spacing: 0 15px;
padding: 10px;
table-layout: fixed;
}
input[type=button]{
border: none;
outline: none;
border-radius: 100%;
height: 100%;
width: 100%;
font-weight: 500;
font-size:large;
}
#calc{
background-color:rgba(240, 248, 255, 0.4);
}
#display{
background-color: rgba(0, 0, 0, 0.4);
}
#prev,#curr{
max-width: 326px;
overflow: auto;
}
#prev{
text-align: right;
font-size: 150%;
margin: 0px 0px 0px 0px;
}
#curr{
text-align: right;
font-size: 400%;
margin: 0px 0px 0px 0px;
}
#display{
height: 150px;
}
tr.keyboard th{
min-width: 80px;
height: 80px;
}
#\/{
background-color: aquamarine;
}
#\/:active{
transition: 0.2s;
font-size: medium;
width: 80%;
height: 80%;
}
#\*{
background-color: lightsalmon;
}
#\*:active{
transition: 0.2s;
font-size: medium;
width: 80%;
height: 80%;
}
#\+{
background-color: cornflowerblue;
}
#\+:active{
transition: 0.2s;
font-size: medium;
width: 80%;
height: 80%;
}
#\-{
background-color: lightpink;
}
#\-:active{
transition: 0.2s;
font-size: medium;
width: 80%;
height: 80%;
}
#\={
background-color: rgb(252, 250, 164);
}
#\=:active{
transition: 0.2s;
font-size: medium;
width: 80%;
height: 80%;
}
#clear,#backspace,#\.,#\37,#\38,#\39,#\34,#\35,#\36,#\31,#\32,#\33,#\30,#invert{
background-color: rgb(234, 238, 255);
}
#clear:active,#backspace:active,#\.:active,#\37:active,#\38:active,#\39:active,#\34:active,#\35:active,#\36:active,#\31:active,#\32:active,#\33:active,#\30:active,#invert:active{
transition: 0.2s;
font-size: medium;
width: 80%;
height: 80%;
}
.swipe-area {
position: absolute;
width: 15px;
left: 0;
top: 0;
height: 100%;
background: #f3f3f300;
z-index: 1;
}
Please forgive me for not providing the online version

.toFixed(2) will give you a string with your decimal place.
var numbers = [
123456,
1234.56,
12345.6
];
numbers.map((item)=>{console.log(item.toFixed(2))});
// 123456.00
// 1234.56
// 12345.60

Okay , so I figured it out!!!
var symbol="";
function openNav(){
document.getElementById("mySidenav").style.width ="100%";
}
function closeNav(){
document.getElementById("mySidenav").style.width ="0px";
}
function getPrevious(){
return document.getElementById("prev").innerText;
}
function setPrevious(num){
document.getElementById("prev").innerText=num;
}
function getCurrent(){
return document.getElementById("curr").innerText;
}
function setCurrent(num){
if(num==""){
document.getElementById("curr").innerText=num;
}
else{
document.getElementById("curr").innerText=getFormattedNumber(num)+symbol;
symbol="";
}
}
function getFormattedNumber(num){
var n = Number(num);
var value = n.toLocaleString("hi-IN");
return value;
}
function reverseNumber(num){
return Number(num.replace(/,/g,''));
}
var operator = document.getElementsByClassName("operator");
var rep=true;
var del;
for(var i=0;i<operator.length;i++){
operator[i].addEventListener("click",function(){
if(this.id=="clear"){
setPrevious("");
setCurrent("");
}
else
if(this.id=="backspace"){
var output=reverseNumber(getCurrent()).toString();
if(output){
output=output.substr(0,output.length-1);
alert(output);
if(output.charAt(output.length-1)=="."){//THIS IS WHERE I MADE THE CHANGES!!!!
rep=true;
}
setCurrent(output);
}
}
else
if(this.id=="invert"){
var output=reverseNumber(getCurrent());
if(output!=""){
output=-output;
setCurrent(output);
}
}
else
if(this.id=="."){
var output=reverseNumber(getCurrent()).toString();
if(output!=""){
if(rep==true){
symbol=this.id;
output=output
setCurrent(output);
rep=false;
}
}
}
else{
var current=getCurrent();
var previous=getPrevious();
if(output=="" && history!=""){
if(isNaN(history[history.length-1])){
history=history.substr(0,history.length-1);
}
}
//write continutation here
}
})
}
var number = document.getElementsByClassName("number");
for(var i=0;i<number.length;i++){
number[i].addEventListener("click",function(){
var output=reverseNumber(getCurrent());
if(output!=NaN){
if(getCurrent().charAt(getCurrent().length-1)=="."){
output=output+(0.1*this.id)
setCurrent(output);
}
else{
output=output+this.id;
setCurrent(output);
}
}
})
}
Thanks to y'all!!

Related

Assign TWO Images to Radio Button

Hi so I have this "product" page (on Fiddle) where I have multiple radio boxes in two classes .choosesize and .choosetea. I want to set up my code where if the 8oz radio button is selected then one set of pictures will appear for all the tea selections and if the 16oz radio button is selected another set of pictures will appear for the tea selections.
I have assigned the small and big images to each tea option but I do not know how to show the small pictures if the small 8oz option is selected.
While you don't have all the "combined" images, I have added a possible solution.
var size = "small"
var teatype = "green"
$('.choosetea input').on('click', function() {
teatype = $(this).attr('data-image');
console.log(size + "_" +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size + "_" +teatype + ']').addClass('active');
$(this).addClass('active');
});
$('.choosesize input').on('click', function() {
size = $(this).attr('data-image');
console.log(size + "_" +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size + "_" +teatype + ']').addClass('active');
$(this).addClass('active');
});
So this will comebine size and teatype, So each image will have the data-image where it should be size_teatype
$(document).ready(function() {
var size = "small"
var teatype = ""
$('.choosetea input').on('click', function() {
teatype = "_"+$(this).attr('data-image');
console.log(size +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size +teatype + ']').addClass('active');
$(this).addClass('active');
});
$('.choosesize input').on('click', function() {
size = $(this).attr('data-image');
console.log(size +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size +teatype + ']').addClass('active');
$(this).addClass('active');
});
//local storage color
//local storage size
// add the value of the added radio boxes in the text box
$('.radios1').change(function(e) {
var selectedValue = parseInt($(this).val());
selectedValue += parseInt($(".radios2").val());
$('#amount').val('$' + selectedValue)
});
//add to cart
});
const sizeSelector = 'input:radio[id=small]';
const colorSelector = 'input:radio[id=green]';
const cartSelector = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const SMALL = 20;
const GREEN = 0;
const CARTBUTTON = 5;
function validityCheck() {
let $size = $(`${sizeSelector}`);
let $color = $(`${colorSelector}`);
let size_flag = $size.is(':checked');
let color_flag = $color.is(':checked');
$('#itemdv1A').toggle(size_flag && color_flag) && $('#itemdv2A').toggle(size_flag && color_flag) && $('#yourbutton').toggle(size_flag && color_flag);
}
});
const sizeSelector1 = 'input:radio[id=small]';
const colorSelector1 = 'input:radio[id=chamomile]';
const cartSelector1 = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const CHAMOMILE = 1;
function validityCheck() {
let $size1 = $(`${sizeSelector1}`);
let $color1 = $(`${colorSelector1}`);
let size_flag1 = $size1.is(':checked');
let color_flag1 = $color1.is(':checked');
$('#itemdv1B').toggle(size_flag1 && color_flag1) && $('#itemdv2B').toggle(size_flag1 && color_flag1) && $('#yourbutton').toggle(size_flag1 && color_flag1)
};
});
const sizeSelector2 = 'input:radio[id=small]';
const colorSelector2 = 'input:radio[id=oolong]';
const cartSelector2 = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const OOLONG = 2;
function validityCheck() {
let $size2 = $(`${sizeSelector2}`);
let $color2 = $(`${colorSelector2}`);
let size_flag2 = $size2.is(':checked');
let color_flag2 = $color2.is(':checked');
$('#itemdv1C').toggle(size_flag2 && color_flag2) && $('#itemdv2C').toggle(size_flag2 && color_flag2) && $('#yourbutton').toggle(size_flag2 && color_flag2);
}
});
document.querySelector('#yourbutton').onclick = function() {
document.querySelector('#itemscart').style.display = "none"
};
/* Basic Styling */
.container {
width: 1200px;
top: 300px;
left: 50px;
padding: 15px;
display: flex;
position: absolute;
}
/* Columns */
.columnleft {
width: 220%;
position: relative;
margin-left: 30px;
}
.columnright {
width: 120%;
top: 10px;
margin-left: 80px;
display: block;
}
/* Left Column */
.columnleft img {
width: 100%;
position: absolute;
opacity: 0;
transition: all 0.3s ease;
}
.columnleft img.active {
opacity: 1;
}
/* Product Description */
.product-description {
border-bottom: 1px solid #E1E8EE;
margin-bottom: 20px;
}
/* Product Color */
.tea-type {
margin-bottom: 30px;
}
.choosetea div {
display: block;
margin-top: 10px;
}
.label {
width: 150px;
float: left;
text-align: left;
padding-right: 9px;
}
.choosetea input {
display: none;
}
.choosetea input+label span {
display: inline-block;
width: 40px;
height: 40px;
margin: -1px 4px 0 0;
vertical-align: middle;
cursor: pointer;
border-radius: 50%;
}
.choosetea input+label span {
border: 4px solid RGB(94, 94, 76)
}
.choosetea input#green+label span {
background-color: #90978b;
}
.choosetea input#chamomile+label span {
background-color: #ffd4a1;
}
.choosetea input#oolong+label span {
background-color: #948e9e;
}
.choosetea input:checked+label span {
background-image: url(check-icn.svg);
background-repeat: no-repeat;
background-position: center;
}
/* SIZE */
.tea-type {
margin-bottom: 30px;
}
.choosesize div {
display: block;
margin-top: 10px;
}
.label {
width: 100px;
float: left;
text-align: left;
padding-right: 9px;
}
.choosesize input {
display: none;
}
.choosesize input+label span {
display: inline-block;
width: 40px;
height: 40px;
margin: -1px 4px 0 0;
vertical-align: middle;
cursor: pointer;
border-radius: 50%;
}
.choosesize input+label span {
border: 4px solid RGB(94, 94, 76)
}
.choosesize input#small+label span {
background-color: #252525;
}
.choosesize input#big+label span {
background-color: #1d1d1d;
}
.choosesize input:checked+label span {
background-image: url(https://noychat.github.io/Folia-Website/check-icn.svg);
background-repeat: no-repeat;
background-position: center;
}
/* Product Price */
.product-price {
margin-top: 40px;
display: flex;
align-items: center;
}
.product-price span {
font-size: 26px;
font-weight: 300;
color: #43474D;
margin-right: 20px;
}
.cart-btn {
display: inline-block;
background-color: RGB(94, 94, 76);
border-radius: 6px;
font-size: 16px;
color: #FFFFFF;
text-decoration: none;
padding: 12px 30px;
transition: all .5s;
}
.cart-btn:hover {
background-color: black;
}
.cart-btn2 {
background-color: RGB(94, 94, 76);
border-radius: 6px;
font-size: 16px;
color: #FFFFFF;
text-decoration: none;
padding: 12px 30px;
transition: all .5s;
width: 20px;
position: absolute;
}
#amount {
margin-right: 10px;
display: inline-block;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 55px;
height: 40px;
padding-left: 10px;
transition: all .5s;
}
#shoppingcart {
width: 360px;
height: 300px;
/* border: 1px solid red; */
}
.item {
margin-right: 10px;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 200px;
height: 30px;
padding-left: 10px;
transition: all .5s;
float: left;
}
.item1 {
margin-right: 10px;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 55px;
height: 30px;
padding-left: 10px;
transition: all .5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header"></div>
<!--close all header portion-->
<div class="container">
<!-- Left Column---Tea Images -->
<div class="columnleft">
<img data-image="oolong" src="https://noychat.github.io/Folia-Website/oolongbig.png" alt=" Big Oolong Can">
<img data-image="chamomile" src="https://noychat.github.io/Folia-Website/chamomilebig.png" alt="Big Chamomile Can">
<img data-image="green" class="active" src="https://noychat.github.io/Folia-Website/greenteabig.png" alt="Big Green Tea Can">
<img data-image="small" class="active" src="https://noychat.github.io/Folia-Website/foliasmall.png" alt="Small Example Can">
<img data-image="big" src="https://noychat.github.io/Folia-Website/foliabig.png" alt="Big Example Can">
<img data-image="small_chamomile" src="https://noychat.github.io/Folia-Website/chamomilesmall.png" alt="Small Chamomile Can">
<img data-image="small_oolong" src="https://noychat.github.io/Folia-Website/oolongsmall.png" alt="Small Oolong Can">
<img data-image="small_green" src="https://noychat.github.io/Folia-Website/greenteasmall.png" alt="Small Green Tea Can">
</div>
<!-- Right Column -->
<div class="columnright">
<!-- Product Description -->
<div class="product-description">
<span>Folia Tea Collection</span>
<h1>Signature Teas</h1>
<p>We source our tea leaves from around the world. Try our many selections of teas and you will taste the difference.</p>
</div>
<!-- Product Configuration -->
<div class="product-configuration">
<!-- Tea Size -->
<div class="tea-type">
<h3>Size</h3>
<div class="choosesize">
<div>
<input data-image="small" type="radio" id="small" name="size" value="20" class="radios1">
<label for="small"><span></span></label>
<div class="label">8 oz</div>
</div>
<div>
<input data-image="big" type="radio" id="big" name="size" value="40" class="radios1">
<label for="big"><span></span></label>
<div class="label">16 oz</div>
</div>
</div>
<!--CLOSE TEA Size-->
<!-- Tea Type -->
<div class="tea-type">
<h3>Tea Type</h3>
<div class="choosetea">
<div>
<input data-image="green" data-image1="small_green" type="radio" id="green" name="color" value="0" class="radios2">
<label for="green"><span></span></label>
<div class="label">Green Tea</div>
</div>
<div>
<input data-image="chamomile" data-image1="small_chamomile" type="radio" id="chamomile" name="color" class="radios2" value="1">
<label for="chamomile"><span></span></label>
<div class="label">Chamomile Tea</div>
</div>
<div>
<input data-image="oolong" data-image1="small_oolong" type="radio" id="oolong" name="color" class="radios2" value="2">
<label for="oolong"><span></span></label>
<div class="label">Oolong Tea</div>
</div>
</div>
</div>
<!--CLOSE TEA TYPE-->
<h3>Product Pricing</h3>
<div class="product-price">
<input type="text" name="amount" id="amount">
<button type="button" class="cart-btn" id="cartbutton" name="cart" value="5">Add To Cart!</button>
</div>
</div>
</div>
<!--close CONTAINER-->
<div id="shoppingcart">
<h3>Shopping Cart</h3>
<h5>Item and Price</h5>
<div id="itemscart">
<div id="itemdv1A" style="display: none"> <input type="text" name="amount" class="item" value="8oz Green Tea"></div>
<div id="itemdv2A" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<div id="itemdv1B" style="display: none"> <input type="text" name="amount" class="item" value="8oz Chamomile Tea"></div>
<div id="itemdv2B" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<div id="itemdv1C" style="display: none"> <input type="text" name="amount" class="item" value="8oz Oolong Tea"></div>
<div id="itemdv2C" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<button style="display: none" type="button" class="cart-btn2" id="yourbutton" name="remove" value="10">x</button>
</div>
</div>

Add Javascript counters to colour counter

I am making a colour counter application, That has has 6 different colours.
I am currently trying to implement a pure JavaScript counter that has a individual counter for each colour.
(Correction: It is not to count the different colours displayed on the page, but when the user sees a colour in their surrounding environment that matches one of the 6 colours, they increase the counter by 1, for example the user sees the sky is blue and the grass is green, The user hovers over the blue colour, the increase and decrease buttons appear, the user increases the blue colour by 1 increment, Then for the grass the user hovers over the green colour, again the button appears and the user increases the green counter by 1.)
When a user hovers over the colour buttons must appear to increase or decrease the counter by 1, to a minimum of 0.
The count of each colour must always be displayed above the colour.
My current method seems rather long I'm sure there is a way to set up some sort of a method to handle all colours but again to have separate counters for each colour.
Please see the below image for what I am trying to achieve:
See this image
Any help would be appreciated,
I have included my current code below for reference
var green = 0;
var countEl1 = document.getElementById("green");
function plus1(){
green++;
countEl1.value = green;
}
function minus1(){
if (green > 0) {
green--;
countEl1.value = green;
}
}
var brown = 0;
var countEl2 = document.getElementById("brown");
function plus2(){
brown++;
countEl2.value = brown;
}
function minus2(){
if (brown > 0) {
brown--;
countEl2.value = brown;
}
}
var blue = 0;
var countEl3 = document.getElementById("blue");
function plus3(){
blue++;
countEl3.value = blue;
}
function minus3(){
if (blue > 0) {
blue--;
countEl3.value = blue;
}
}
var yellow = 0;
var countEl4 = document.getElementById("yellow");
function plus4(){
yellow++;
countEl4.value = yellow;
}
function minus4(){
if (yellow > 0) {
yellow--;
countEl4.value = yellow;
}
}
var gold = 0;
var countEl5 = document.getElementById("gold");
function plus5(){
gold++;
countEl5.value = gold;
}
function minus5(){
if (gold > 0) {
gold--;
countEl5.value = gold;
}
}
var red = 0;
var countEl6 = document.getElementById("red");
function plus6(){
red++;
countEl6.value = red;
}
function minus6(){
if (red > 0) {
red--;
countEl6.value = red;
}
}
.pyramid {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
width: 100vmin;
aspect-ratio: 9 / 15; /* 2/1 */
background-color: white;
display: grid;
grid-template-columns: 1fr;
}
.pyramid > * {
background: white;
}
.one {
background-color: rgba(234, 27, 7, 0.97);
}
.two {
background-color: rgba(244, 182, 0, 0.98);
margin-top: 10px;
}
.three {
background-color: rgba(249, 224, 41, 0.98);
margin-top: 10px;
}
.four {
background-color: rgba(4, 157, 252, 0.98);
}
.five {
background-color: rgba(167, 118, 67, 0.99);
gap: 0% !important;
}
.six {
background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
display: inline-block;
width: 20px;
background-color: transparent;
outline: none;
border: none;
text-align: center;
cursor: pointer;
padding: 0px;
color: black;
height: 33px;
font-family: 'Open Sans';
}
#container {
width: 100px;
height: 100px;
position: relative;
}
#navi,
#infoi {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
#infoi {
z-index: 10;
}
button {
border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Colour counter</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/Main.js"></script>
</head>
<body>
<div id="container">
<h1>Colour counter</h1>
<div class="pyramid">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
</div>
<h1>Counter Test</h1>
<div id="input_div">
<input type="button" value="-" id="minus1" onclick="minus1()">
<input type="text" size="25" value="0" id="green">
<input type="button" value="+" id="plus1" onclick="plus1()">
<script src="js/Main.js"></script>
</div>
<div id="input_div2">
<input type="button" value="-" id="minus2" onclick="minus2()">
<input type="text" size="25" value="0" id="brown">
<input type="button" value="+" id="plus2" onclick="plus2()">
<script src="js/Main.js"></script>
</div>
</div>
</body>
</html>
Use an array from which do the operations on the DOM and apply map to do each colour's job, which would be to programatically attach the event listener to the DOM elements. Also, ensure the DOM has fully loaded before running your JS code:
window.onload = function() {
let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
.map(id => {
let colour = {
elementCount: document.getElementById(id),
elementPlus: document.getElementById(`${id}_plus`),
elementMinus: document.getElementById(`${id}_minus`),
counter: 0,
};
colour.elementPlus.addEventListener("click", function() {
colour.counter++;
colour.elementCount.value = colour.counter;
});
colour.elementMinus.addEventListener("click", function() {
if (colour.counter > 0) {
colour.counter--;
colour.elementCount.value = colour.counter;
}
});
return colour;
});
};
Adapt the HTML so the IDs match the ones used in the JS:
Instead of minus1, use green_minus. Do the same for the rest of minus buttons.
Instead of plus1, use green_minus. Do the same for the rest of plus buttons.
Adapt the HTML removing the onClick attribute (it is now assigned programatically using JS).
As a plus, now you have the colours variable, where all the DOM elements and each colour counter are stored for further inspection and or modification.
As an example, one colour in the HTML would be like:
<div id="input_div">
<input type="button" value="-" id="green_minus">
<input type="text" size="25" value="0" id="green">
<input type="button" value="+" id="green_plus">
</div>
<!-- Other colours... -->
<script src="js/Main.js"></script>
window.onload = function() {
let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
.map(id => {
let colour = {
elementCount: document.getElementById(id),
elementPlus: document.getElementById(`${id}_plus`),
elementMinus: document.getElementById(`${id}_minus`),
counter: 0,
};
colour.elementPlus.addEventListener("click", function() {
colour.counter++;
colour.elementCount.value = colour.counter;
});
colour.elementMinus.addEventListener("click", function() {
if (colour.counter > 0) {
colour.counter--;
colour.elementCount.value = colour.counter;
}
});
return colour;
});
};
.pyramid {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
width: 100vmin;
aspect-ratio: 9 / 15; /* 2/1 */
background-color: white;
display: grid;
grid-template-columns: 1fr;
}
.pyramid > * {
background: white;
}
.one {
background-color: rgba(234, 27, 7, 0.97);
}
.two {
background-color: rgba(244, 182, 0, 0.98);
margin-top: 10px;
}
.three {
background-color: rgba(249, 224, 41, 0.98);
margin-top: 10px;
}
.four {
background-color: rgba(4, 157, 252, 0.98);
}
.five {
background-color: rgba(167, 118, 67, 0.99);
gap: 0% !important;
}
.six {
background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
display: inline-block;
width: 20px;
background-color: transparent;
outline: none;
border: none;
text-align: center;
cursor: pointer;
padding: 0px;
color: black;
height: 33px;
font-family: 'Open Sans';
}
#container {
width: 100px;
height: 100px;
position: relative;
}
#navi,
#infoi {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
#infoi {
z-index: 10;
}
button {
border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Colour counter</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/Main.js"></script>
</head>
<body>
<div id="container">
<h1>Colour counter</h1>
<div class="pyramid">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
</div>
<h1>Counter Test</h1>
<div id="input_div">
<input type="button" value="-" id="green_minus">
<input type="text" size="25" value="0" id="green">
<input type="button" value="+" id="green_plus">
</div>
<div id="input_div2">
<input type="button" value="-" id="brown_minus">
<input type="text" size="25" value="0" id="brown">
<input type="button" value="+" id="brown_plus">
</div>
<div id="input_div3">
<input type="button" value="-" id="blue_minus">
<input type="text" size="25" value="0" id="blue">
<input type="button" value="+" id="blue_plus">
</div>
<div id="input_div4">
<input type="button" value="-" id="yellow_minus">
<input type="text" size="25" value="0" id="yellow">
<input type="button" value="+" id="yellow_plus">
</div>
<div id="input_div5">
<input type="button" value="-" id="gold_minus">
<input type="text" size="25" value="0" id="gold">
<input type="button" value="+" id="gold_plus">
</div>
<div id="input_div6">
<input type="button" value="-" id="red_minus">
<input type="text" size="25" value="0" id="red">
<input type="button" value="+" id="red_plus">
</div>
</div>
</body>
</html>
I have made a variaton adding dinamically colors using an input so you can call any color name you want.
Put the buttons above each color is kinda dificult because you are using a polygon, so in this example the button are in the left side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Colour counter</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/Main.js"></script>
<style>
.grid {
display: flex;
text-align: center;
max-width: 480px;
}
.grid .counter {
margin-right: 15px;
}
.counter .column {
text-align: center;
vertical-align: middle;
}
.column {
height: 100px;
width: 100px;
display: flex;
align-content: center;
justify-content: center;
align-items: center;
}
.form {
margin: 10px 0;
}
.form input[type='text'] {
margin: 3px 0;
border: 1px solid black;
width: 200px;
}
input[type='button'] {
border: 1px solid black;
margin: 0 4px;
}
.pyramid {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
width: 300px;
aspect-ratio: 9 / 15;
/* 2/1 */
background-color: white;
display: grid;
grid-template-columns: 1fr;
}
.pyramid>* {
background: white;
}
.counter input[type=button],
input[type=text] {
display: inline-block;
width: 20px;
background-color: transparent;
outline: none;
border: none;
text-align: center;
cursor: pointer;
padding: 0px;
color: black;
height: 33px;
font-family: 'Open Sans';
}
#container {
width: 100px;
height: 100px;
position: relative;
}
button {
border-radius: 50%;
}
</style>
</head>
<body>
<div class="color-counter">
<h1>Colour counter</h1>
</div>
<div class="form">
<form>
<label for="fcolour">Enter the colour name: </label>
<br>
<input id="fcolour" type="text" name="fcolour">
<br>
<input type="button" value="Submit">
</form>
</div>
<div id="container">
<div class="grid">
<div class="counter">
</div>
<div class="pyramid">
</div>
</div>
</div>
<script>
document.querySelector('form input[type="button"]').addEventListener('click', function (e) {
var colCounter = document.querySelector('.grid .counter')
var colPyramid = document.querySelector('.grid .pyramid')
var colorName = document.getElementById('fcolour').value
var newCounterChild = document.createElement('div')
newCounterChild.classList.add('column')
newCounterChild.innerHTML = `
<input type="button" value="-" id="minus_${colorName}">
<input type="text" size="25" value="0" id=counter_${colorName}>
<input type="button" value="+" id="plus_${colorName}">
`
colCounter.appendChild(newCounterChild)
var newPyramidChild = document.createElement('div')
newPyramidChild.classList.add('column')
newPyramidChild.style.backgroundColor = colorName
newPyramidChild.style.marginTop = '10px'
colPyramid.appendChild(newPyramidChild)
document.getElementById(`plus_${colorName}`).addEventListener('click', function (v) {
document.getElementById(`counter_${colorName}`).value++
})
document.getElementById(`minus_${colorName}`).addEventListener('click', function (v) {
var val = document.getElementById(`counter_${colorName}`)
val.value > 0 ? val.value-- : null
})
})
</script>
</body>

HTML Form resets my Javascript variable [duplicate]

This question already has answers here:
How to prevent buttons from submitting forms
(20 answers)
Closed 4 years ago.
Good day!
My form has javascript functions for my buttons for adding rows from table and resetting the text fields in the form itself.
In my add button, I have an incrementing variable, rowCount, for counting the row. It works well and works what I expected. When I put it inside the <form></form> tag, it stuck at 2, doesn't increment and doesn't add rows at all.
Here's my code for our reference and also to be debugged. Thanks in advance!
var rowCount = 1;
function addRow() {
var table = document.getElementById('tblOrder');
rowCount = rowCount + 1;
var row = table.insertRow(rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
cell0.innerHTML = "<input type='text'>";
cell1.innerHTML = "<input type='number'>";
cell2.innerHTML = "<input type='text'>";
cell3.innerHTML = "<input type='text'>";
cell4.innerHTML = "<input type='text'>";
cell5.innerHTML = "<input type='text'>";
alert(rowCount)
}
function resetForm() {
document.getElementById('orderForm').reset();
alert('All cleared!')
}
body {
font-family: Calibri;
font-weight: bold;
}
#main {
width: 90%;
border: 1px solid black;
margin: auto;
position: relative;
padding-bottom: 10px;
}
#mainTitle {
text-align: center;
text-decoration: underline;
/* font-weight: bold; */
font-size: 36px;
margin-top: 20px;
margin-bottom: 20px;
}
#cust, #prod {
width: 90%;
position: relative;
margin: auto;
border: 1px solid black;
padding: 20px;
}
#cust {
margin-bottom: 20px;
}
#prod {
margin-bottom: 10px;
}
#custTitle, #prodTitle {
color: blue;
font-size: 25px;
/* font-weight: bold; */
text-decoration: underline;
margin-bottom: 20px;
/* position: relative; */
}
#cust p {
display: block;
}
#cust input {
display: inline;
}
#right {
position: absolute;
top: 0;
right: 0;
padding: 10px;
/* border: 1px solid black; */
}
#right p {
right: 0;
}
#tblOrder {
width: 100%;
border: 1px solid black;
}
#tblOrder thead {
background-color: darkgreen;
color: white;
font-size: 18px;
}
#tblOrder td {
text-align: center;
padding: 5px;
}
#inp1 {
width: 5%;
}
#inp2 {
width: 10%;
}
#inp3, #inp5, #inp6 {
width: 15%;
}
#inp4 {
width: 40%;
}
#tblOrder tr td input {
width: 95%;
}
#add {
color: blue;
font-weight: bold;
background-color: white;
border: 1px solid white;
margin-top: 10px;
}
#foot {
position: relative;
width: 90%;
margin: auto;
/* border: 1px solid black; */
}
#buttons {
position: relative;
left: 0;
/* display: inline; */
}
#total {
position: absolute;
right: 0;
/* display: inline; */
}
<!DOCTYPE html>
<html>
<head>
<title>Forms</title>
<link type='text/css' rel='stylesheet' href='style.css'>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<div id='main'>
<div id='mainTitle'>
Order Form
</div>
<form id='orderForm'>
<div id='cust'>
<div id='custTitle'>
Customer
</div>
<div id='left'>
<p>Customer Name: <input type='text' size=80></p>
<p>Address: <input type='text' size=100></p>
<p>Contact Name: <input type='text' size=80></p>
<p>Phone: <input type='text' size=15>
Mobile: <input type='text' size=15></p>
<p>E-mail Address: <input type='text' size=30>#<input type='text' size=10>.com</p>
</div>
<div id='right'>
<p>Order Date: <input type='text' placeholder='mm/dd/yyyy' size=11></p>
<p>Order Number: <input type='text' size=5></p>
</div>
</div>
<div id='prod'>
<div id='prodTitle'>
Products to Order
</div>
<div id='order'>
<table id='tblOrder'>
<thead>
<td id='inp1'>Unit</td>
<td id='inp2'>Quantity</td>
<td id='inp3'>Product Code</td>
<td id='inp4'>Description</td>
<td id='inp5'>Unit Price</td>
<td id='inp6'>Total Price</td>
</thead>
<tbody>
<tr>
<td><input type='text'></td>
<td><input type='number'></td>
<td><input type='text'></td>
<td><input type='text'></td>
<td><input type='text'></td>
<td><input type='text'></td>
</tr>
</tbody>
</table>
<button id='add' onclick='addRow()'>+Row</button>
</div>
</div>
<div id='foot'>
<div id='total'>
Total: <input type='text' disabled>
</div>
<div id='buttons'>
<button>Submit</button>
<button onclick='resetForm()'>Reset</button>
</div>
</div>
</form>
</div>
</body>
</html>
If buttons are put inside a form, they become submit buttons by default, meaning they submit the form when clicked. If the form doesn't have an action specified, it will be submitted to the same URL as the page, which results in the page being refreshed. This is what happens in your case.
To prevent a button from submitting the form, set its type to be a generic button instead of a submit button:
<button type="button"></button>

jQuery animation doesn't work with SAPUI5

I'm constructing a tree-view that slides out based on the buttons the user clicks in the preceding column. I get this error when I click on the first column of buttons:
Uncaught TypeError: $(...).effect is not a function
at runEffect1 (test:39)
at HTMLDivElement.<anonymous> (test:66)
at HTMLDivElement.dispatch (jquery-dbg.js:4737)
at HTMLDivElement.c3.handle (jquery-dbg.js:4549)
How do I fix it? These functions worked when I used vanilla JavaScript and without the SAPUI5 imported, but using jQuery now gives problems. I need to use SAPUI5 with jQuery. Also, the snippet doesn't work due to adding SAPUI5.
$(document).ready(function() {
$(function() {
// run the currently selected effect
function runEffect1() {
var selectedEffect = "slide";
var options = {};
/* Hide the columns so that they can slide into display*/
$("#column_2").hide();
$("#column_3").hide();
$("#column_4").hide();
// Run the effect
$("#column_2").effect(selectedEffect, options, 450, function() {
$("#column_3").effect(selectedEffect, options, 450, function() {
$("#column_4").effect(selectedEffect, options, 450, callback);
});
});
};
// Callback function to bring a hidden box back
function callback() {
setTimeout(function() {
$("#effect").removeAttr("style").hide().fadeIn();
}, 100);
};
// Set effect from select menu value
$("#column_1").on("click", function() {
runEffect1();
return false;
});
$("#column_2").on("click", function() {
runEffect2();
return false;
});
});
});
function myFunction2(e) {
test = e;
console.log(e);
jQuery("#column_2").html("");
jQuery("#column_2").html("<span style='color:#FFFFFF'> GL Accounts </span>");
jQuery("#column_3").html("");
jQuery("#column_3").html("<span style='color:#FFFFFF'> GL Name </span>");
jQuery("#column_4").html("");
jQuery("#column_4").html("<span style='color:#FFFFFF'> GL Balance </span>");
jQuery("#column_5").html("");
for (var prop3 in array0) {
jQuery("#column_2").append('<div class="col-md-auto"> <button type="button" id=' + prop3 + ' class="list-group-item" onclick="myFunction4(this.id)">test</button></div>');
jQuery("#column_3").append('<div class="col-md-auto"> <button type="button" id=' + prop3 + ' class="list-group-item" onclick="myFunction4(this.id)">test1</button></div>');
jQuery("#column_4").append('<div class="col-md-auto"> <button type="button" id=' + prop3 + ' class="list-group-item" onclick="myFunction4(this.id)">test2</button></div>');
}
for (var prop2 in array17) {
jQuery("#column_4").append('<div class="col-md-auto"> <button type="button" id=' + prop2 + ' class="list-group-item" onclick="myFunction2(this.id)">test3</button></div>');
}
}
function myFunction4(e) {
test = e;
console.log(e);
jQuery("#column_5").html("");
jQuery("#column_5").html("<span style='color:#FFFFFF'> Breakdown </span>");
for (var prop5 in array11) {
jQuery("#column_5").append('<div class="col-md-auto"> <button type="button" id=' + prop5 + ' class="list-group-item" onclick="myFunction5(this.id)">test4</button></div>');
}
}
function myFunction5(e) {
test = e;
console.log(e);
window.open("", "", "width=500,height=500");
}
sap.ui.getCore().attachInit(function() {
console.log("SAPUI5 modules loaded....")
jQuery("#column_1").html("");
jQuery("#column_1").html("<span style='color:#FFFFFF'> Account Group </span>");
for (var prop in array2) {
jQuery("#column_1").append('<div class="col-md-auto"> <button type="button" id=' + prop + ' class="list-group-item" onclick="myFunction2(this.id)">test0</button></div>');
}
});
#import url(https://fonts.googleapis.com/css?family=Roboto:300);
.login-page {
width: 360px;
padding: 8% 0 0;
margin: auto;
}
.form {
position: relative;
z-index: 1;
background: #FFFFFF;
max-width: 360px;
margin: 0 auto 100px;
padding: 45px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}
.form input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;
font-size: 14px;
}
.form button {
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #4778b7;
width: 100%;
border: 0;
padding: 15px;
color: #FFFFFF;
font-size: 14px;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
cursor: pointer;
}
.form button:hover,
.form button:active,
.form button:focus {
background: #7ac1db;
}
.form .message {
margin: 15px 0 0;
color: #b3b3b3;
font-size: 12px;
}
.form .message a {
color: #4CAF50;
text-decoration: none;
}
.form .register-form {
display: none;
}
.container {
position: relative;
z-index: 1;
max-width: 300px;
margin: 0 auto;
}
.container:before,
.container:after {
content: "";
display: block;
clear: both;
}
.container .info {
margin: 50px auto;
text-align: center;
}
.container .info h1 {
margin: 0 0 15px;
padding: 0;
font-size: 36px;
font-weight: 300;
color: #1a1a1a;
}
.container .info span {
color: #4d4d4d;
font-size: 12px;
}
.container .info span a {
color: #000000;
text-decoration: none;
}
.container .info span .fa {
color: #EF3B3A;
}
body {
background: #4778b7;
/* fallback for old browsers */
background: -webkit-linear-gradient(right, #4778b7, #4778b7);
background: -moz-linear-gradient(right, #4778b7, #4778b7);
background: -o-linear-gradient(right, #4778b7, #4778b7);
background: linear-gradient(to left, #4778b7, #4778b7);
font-family: "Roboto", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
<html>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-xx-bindingSyntax="complex" data-sap-ui-libs="sap.m" data-sap-ui-theme="sap_bluecrystal">
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
<div id="grid" class="container-fluid">
<div class="row no-gutter">
<div class="col-md-2">
<div id="column_1">
<div class="list-group"></div>
<div class='col-md-auto'>
<button type='button' id=1 class='list-group-item'>test</button>
</div>
</div>
</div>
<div class="col-md-2 ">
<div id="column_2">
<div class="list-group"></div>
</div>
</div>
<div class="col-md-2 ">
<div id="column_3">
<div class="list-group"></div>
</div>
</div>
<div class="col-md-2 ">
<div id="column_4">
<div class="list-group"></div>
</div>
</div>
<div class="col-md-2">
<div id="column_5">
<div class="list-group"></div>
</div>
</div>
</div>
</div>
</body>
</html>
it was sap-ui-core.js causing problem; using jQuery noConflict.
$.noConflict();
$(document).ready(function() {
...
});
Normally you don't need the following code in your HTML, because they are duplicated
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
And where did you place the js code? The $(document).ready(function(){ one. It must be place after the all of the js library.

javascript while loop not performing functions inside

I'm a student and new so I'm sorry if my formatting is off. I am having a problem with my while loop not executing the main functions inside the loop. I'm not sure what I'm doing wrong. I am making a tic tac toe game with a mario theme and a fair amount is working but my while loop runs through itself until it hits 'i = 9' and it seems to increase my marioCount to 9 as well but my goal was to have it alternate between classes when I click on a new box and that doesn't work. I always get bowser. Please help if possible and go easy on me, i'm a beginner. Thanks in advance.
$(document).ready(function() {
var $quare = $('.square');
var $brd = $('.board');
var $tart = $('#start');
var $bmario = $('#mario');
var $bbowser = $('#bowser');
var $cchar = $('#cchar');
var clickedSquare = 0;
var bowserCount = 0;
marioCount = 0;
$cchar.hide();
$bmario.hide();
$bbowser.hide();
$brd.hide();
$tart.on('click', function revealButton() {
$bmario.show();
$bbowser.show();
$cchar.show();
})
$bmario.on('click', function() {
$brd.show();
$bbowser.hide();
var i = 0
while (i < 9) {
if(marioCount % 2 === 0) {
$quare.on('click', function() {
$(this).addClass('smario clicked');
})
} else {
$quare.on('click', function() {
$(this).addClass('sbowser clicked');
})
}
marioCount++
i++
}
})
})
This is the HTML for my game
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mario Tic Tac Toe</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div id="allBody">
<div id="header">
<div id="title">Tic Tac Toe</div>
</div>
<div id="startDiv">
<button class="button" id="start">Start Game</button>
</div>
<div id="cchar">Pick Your Character</div>
<div id="choose">
<button class="button" id="mario"></button>
<button class="button" id="bowser"></button>
</div>
<div class="board">
<table class="tabl">
<!-- <tbody id="tbody"> -->
<tr id="row1">
<td class="square " id="square1"></td>
<td class="square vmiddle" id="square2"></td>
<td class="square" id="square3"></td>
</tr>
<tr id="row2">
<td class="square hmiddle" id="square4"></td>
<td class="square vmiddle hmiddle" id="square5"></td>
<td class="square hmiddle" id="square6"></td>
</tr>
<tr id="row3">
<td class="square" id="square7"></td>
<td class="square vmiddle" id="square8"></td>
<td class="square" id="square9"></td>
</tr>
<!-- </tbody> -->
</table>
<!-- Game Here -->
</div>
<div id="info">...</div>
</div>
<script src="js/jquery-2.2.0.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Here's the CSS for the game
html {
background: url(http://i1.kym-cdn.com/photos/images/original/000/939/881/cf4.png) no-repeat center center fixed;
background-size: cover;
}
#title {
text-align: center;
color: yellow;
font-size: 50px;
}
#startDiv {
text-align: center;
margin: 0 auto;
}
#choose {
text-align: center;
margin: 0 auto;
}
#mario {
background: url("../images/Mario_super_cool.jpg");
background-size: cover;
height: 35px;
width: 35px;
}
#bowser {
background: url("../images/Bowser.jpg");
background-size: cover;
height: 35px;
width: 35px;
}
#cchar {
color: yellow;
text-align: center;
font-size: 30px;
}
#start {
text-align: center;
margin: 0 auto;
border-radius: 15px;
color: yellow;
font-size: 35px;
}
.smario {
background: url("../images/Mario_super_cool.jpg");
background-size: cover;
height: 125px;
width: 125px;
}
.sbowser {
background: url("../images/Bowser.jpg");
background-size: cover;
height: 125px;
width: 125px;
}
.board {
}
table {
margin: auto;
background: rgba(171, 39, 7, 0.5);
}
.square {
float: left;
font-family: 'Londrina Shadow', cursive;
font-size: 50px;
height: 125px;
margin: 0px;
text-align: center;
vertical-align: middle;
width: 125px;
}
.vmiddle {
border-left: 5px solid yellow;
border-right: 5px solid yellow;
opacity: 1.4;
}
.hmiddle {
border-top: 5px solid yellow;
border-bottom: 5px solid yellow;
}
You don't need a loop here. Have a look at this code.
$(".square").on("click", function () {
if (!$(this).hasClass("clicked")) { // do something if this square hasn't been clicked
if (marioCount % 2 === 0) {
$(this).addClass("smario clicked");
} else {
$(this).addClass('sbowser clicked');
}
marioCount++;
}
});
Replace "< 9" with "< 10", since you are essentially saying "do this while i is 8 or less, but NOT 9", instead of what you want, "do this while i is 9 or less, but NOT 10".

Categories

Resources