How to add 1 to html content with every click using javascript - javascript

New to coding, especially javascript.
My function is not working. When I open the web page and click the button, the number still just appears as 100.
Any idea how to fix this so that with each click of the button the number increases by 1?
var number = document.getElementById("a");
var count = 0;
number.innerHTML = count;
number.onClick = function() {
count += 1;
};
.dev {
display: block;
font-size: 30px;
font-weight: bold;
text-align: center;
vertical-align: middle;
}
<button id="a" class='dev'> </button>

Try:
<button id="a" onclick="increment();"> </button>
function increment()
{
var inc = parseInt(document.getElementById('a').value);
inc = isNaN(value) ? 0 : value;
inc++;
document.getElementById('a').value = inc;
}

Just spell onClick to 'onclick' and put 'number.innerHTML = count;' inside function.
<!DOCTYPE html>
<!-- CSS -->
<style>
dev {
display: block;
font-size: 30px;
font-weight: bold;
text-align: center;
vertical-align: middle;
}
</style>
<!-- HTML -->
<html>
<button id="a">0 </button>
</html>
<!-- JAVASCRIPT -->
<script>
var number = document.getElementById("a");
var count = 0;
number.onclick = function() {
count += 1;
number.innerHTML = count;
};
</script>

Use the addEventListener and add the click event.
var number = document.getElementById("a");
var count = 0;
number.innerHTML = count;
number.addEventListener('click', function() {
const cnt = Number(number.innerHTML) + 1
number.innerHTML = cnt
});
dev {
display: block;
font-size: 30px;
font-weight: bold;
text-align: center;
vertical-align: middle;
}
<html>
<button id="a"> </button>
</html>

number.onClick = function() {
count += 1;
};
onClick should be replaced with onclick
Javascript is a case sensitive language, so onClick and onclick are treated as 2 different words.
On clicking, you are just changing the value of count variable, but not updating DOM(Document Object Model).
So the final code should be
number.onclick = function() {
count += 1;
number.innerHTML = count;
};

Just put this line in the function
number.innerHTML = count;
.
number.onclick = function() {
count += 1;
number.innerHTML = count;
};

Related

Sequential animations on HTML element

guys. I'm trying to create a group of sequential "animations" through css classes on my buttons, but i keep getting a problem where all my buttons receive the effect on the same time and not one after another.
The function playAllSequence should hightlight each button one after another following the sequence present in an array.
I've already tried to put the setTimeOut function inside a closure and tried changed my declaration to let instead of var.
What am i missing?
Thanks in advance
// Get number of buttons on the document
var numberOfButtons = document.querySelectorAll(".btn").length;
var collectionButtonsClicked = [];
var collectionOfRandomColors = [];
var buttonsColors = ["blue", "green", "red", "yellow"];
var gameTitle = document.querySelector("#level-title");
// detecting clicks on the buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].addEventListener("click", function () {
collectionButtonsClicked.push(this.id);
// call click animation function
clickAnimation ();
// Only checks when arrays have the same length so the user have to click all the sequence again
if (collectionButtonsClicked.length === collectionOfRandomColors.length) {
checkClick();
}
})};
// detecting button press to start the game
document.addEventListener("keydown", function (event) {
if (event.key === "a") {
gameTitle.innerHTML = "Game Started";
generateRandomColor();
playAllSequence();
}
});
// check if the click is correct
function checkClick () {
// if correct - Generate new color, disable buttons and play the sequence on all buttons
let arrayRandomStringfied = JSON.stringify(collectionOfRandomColors);
let arrayClickedStringfied = JSON.stringify(collectionButtonsClicked);
if (arrayRandomStringfied === arrayClickedStringfied) {
generateRandomColor();
playAllSequence();
console.log("acertou!")
// erasing click array so the player has to click all the color again
collectionButtonsClicked = [];
} else {
//call fail animation function
failAnimation();
// function to reset the arrays and the title
restartGame();
console.log("errou!")
}
}
//Generate random color and return array - User will have to follow this colors
function generateRandomColor () {
let randomIndex = Math.floor(Math.random() * 4);
collectionOfRandomColors.push(buttonsColors[randomIndex]);
return collectionOfRandomColors;
}
function playAllSequence () {
// disabling all buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = true;
}
for ( let i = 0; i < collectionOfRandomColors.length; i++ ) {
doSetTimeOut(i);
}
// Enabling all buttons again
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = false;
}
}
function doSetTimeOut (i) {
let activeButton = document.querySelector("." + collectionOfRandomColors[i]);
// Add pressed effect
activeButton.classList.add("pressed");
// Remove pressed effect after 1 second
setTimeout(function() {
activeButton.classList.remove("pressed")
}, 1000);
}
function clickAnimation () {
}
function failAnimation () {
}
function restartGame () {
collectionOfRandomColors = [];
collectionButtonsClicked = [];
gameTitle.innerHTML = "Press A key to Start";
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Well, I don't see your sample code to animate even the first button.
If you need independent separate events to happen '1 by 1' visually, you might use a i*1000 as a setTimeout second argument.
If not, here's the code doing something close to what you want to achieve, i believe. Define a function that sets the props you need (box-shadow in this example) for an element taken by index, and sets timeout for a function that will remove the props and call the first function again with the next index:
function animateBtnsSequence( i ){
var btns = document.querySelectorAll(".btn");
btns[i].style.boxShadow = '0 0 20px 1px white';
window.setTimeout(function(){
btns[i].style.boxShadow = '';
if( btns[i+1] )
animateBtnsSequence( i + 1 );
}, 1000)
}
function playAllSequence () {
animateBtnsSequence( 0 );
}

Incrementing variable id using javascript button onclick event

im trying to increment the id of an element everytime i click a button
im confused why its working when for innerHTML but not for id
my markup
<p id="demo"></p>
<button onclick="myfunction()">press me</button>
incrementing inner html
<script>
var a = 1;
function myfunction(){
document.getElementById("demo").innerHTML = a;
a++;
}
</script>
incrementing element variable id
<button onclick="myfunction()">press me</button>
<script>
var a = 1;
function myfunction(){
document.getElementById("demo").id = a;
a++;
}
</script>
Please enjoy this demo on storing an element into a variable for reuse. It looks like your issue was with trying to select the element by id after the id changed.
let cntr = 1;
const demo = document.getElementById("demo");
document.querySelector("button")
.addEventListener("click", function () {
const val = cntr % 4;
demo.id = "ele" + val;
cntr++;
});
.demo {
height: 5rem;
aspect-ratio: 1;
border-radius: 50%;
background: black;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
transition: background 1s;
}
#ele1 {
background: pink;
}
#ele2 {
background: lightblue;
}
#ele3 {
background: lightgreen;
}
<div id="demo" class="demo"><button>Clicky!</button></div>

Update element with ajax don't affect until for loop end

I want to print a lot of numbers ONE-BY-ONE with AJAX.
something like this: (each new line is update of previous line!)
output is:
1
12
123
1234
12345
123456
...
I tried a lot and read a lot of this same problem, but i couldn't find my right Answer.
The real problem is every FOR LOOP in javascript will NO affect the DOM after it will END the loop. I just want update the DOM inside the FOR LOOP while working on a long running job.
Please look at my code.
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
setTimeout(function() {
var counter = 100; // i want assign counter = 2000000000
for (var i = 0; i < counter; i++) {
document.getElementById("print_here").innerHTML += i;
}
document.getElementById("foo").innerHTML = "done!";
}, 50);
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
Thanks for any answer and help to solve this problem.
Your DOM is "locked" while it is being updated and redrawn ones the loop is done. You can free up the resource to let the DOM update each time wrapping your DOM change in a setTimeout, similar to:
setTimeout(function(){
document.getElementById("print_here").innerHTML += i;
},1);
To ensure setTimeout uses the correct value for i use let i instead of var i
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
var counter = 3000; // i want assign counter = 2000000000
for (let i = 0; i < counter; i++) {
setTimeout(function() {
document.getElementById("print_here").innerHTML += i;
}, 1);
}
document.getElementById("foo").innerHTML = "done!";
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
I want change the #foo into "done!" after the FOR statement is END
You could check if you are at your last item you process within the setTimeout, similar to:
if (i == counter - 1){
document.getElementById("foo").innerHTML = "done!";
}
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
var counter = 3000; // i want assign counter = 2000000000
for (let i = 0; i < counter; i++) {
setTimeout(function() {
document.getElementById("print_here").innerHTML += i;
if (i == counter - 1){
document.getElementById("foo").innerHTML = "done!";
}
}, 1);
}
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
You need to let the call stack complete so the browser can do its work on the page. If you bog down the one main thread, page updates aren't going to occur.
One way to do this is use setImmediate or nextTick. This is non-standard, so check this polyfill: https://www.npmjs.com/package/browser-next-tick
Basically, you do an iteration, then tell the browser to do the next iteration as soon as possible... and this occurs on a fresh call stack.
Here is the working code for you:
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
setTimeout(function() {
var i, j, row = 5;
var html = "";
for (i = 1; i <= row; i++) {
for (j = 1; j <= i; j++) {
html += "<span>" + j + "</span>";
}
html += "</br>";
}
console.log(html);
document.getElementById("print_here").innerHTML = html;
}, 50);
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
Rows is the number of rows you want to print.

Create multiple textareas in a loop with different ids

I create the checkout page of an eshop and I have a loop in which I display the products that the user has added to the cart. Inside the loop, I display the info for the products I have a text area so the user can choose the quantity of each product. The problem is that the id of each text area must be unique. How can I create many textareas in a loop with different ids?
textarea:
<form name='txtAreaForm' method='GET'>
<textarea disabled name='textArea' id='counter'></textarea>
</form>
Also, I have two buttons (+-) to change the value of the textarea, this is the .js file:
var counter = 1;
// Display total
$("#counter").text(counter);
// When button is clicked
$("#plusButton").click(function(){
counter = counter + 1;
$("#counter").text(counter);
});
//Subtract
$("#minusButton").click(function(){
if (counter>1) {
counter = counter - 1;
$("#counter").text(counter);
}
});
Though the question is not quite clear to me, you can do something like the following:
var counter = 1;
// Display total
$("#counter").text(counter);
var counter = counter + 1;
for(var i=0; i<5; i++){
$("form").append('<textarea name=textArea"+counter+" id=counter"+counter+">1</textarea><input class="plus" type="button" value="+" /><input class="minus" type="button" value="-" /><br>');
}
// When button is clicked
$(".plus").click(function(){
var txtArea = $(this).prev('textarea').text();
$(this).prev('textarea').text(parseInt(txtArea)+1);
});
//Subtract
$(".minus").click(function(){
var txtArea = $(this).prev().prev('textarea').text();
if(txtArea >=2){
$(this).prev().prev('textarea').text(parseInt(txtArea)-1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='txtAreaForm' method='GET'>
</form>
You can use just JavaScript to render a form with as many textareas with its id as necessary and set the actions to each button related to each of them.
See this demo:
(function() {
// Set the plus action on every button with the class name «plus».
function setPlusAction() {
function plus(e) {
var textarea = e.target.previousSibling; // Find the textarea element related to the button clicked.
textarea.value = textarea.value * 1; // Convert the value into number.
textarea.value++; // Increment its value.
}
var elems = document.getElementsByClassName("plus"), i, len = elems.length, button;
for (i = 0; i < len; i++) {
button = elems[i]; // Find the current button.
button.onclick = plus; //Set the «plus» function on every button which has been found.
}
}
// Set the minus action on every button with the class name «minus».
function setMinusAction() {
function minus(e) {
var textarea = e.target.previousSibling.previousSibling; // Find the textarea element related to the button clicked.
textarea.value = textarea.value * 1; // Convert the value into number.
if (textarea.value > 1) {
textarea.value--; // Decrement its value.
}
}
var elems = document.getElementsByClassName("minus"), i, len = elems.length, button;
for (i = 0; i < len; i++) {
button = elems[i]; // Find the current button.
button.onclick = minus; //Set the minus function on every button which has been found.
}
}
// Render a form with the quantity of textareas required.
function buildForm(textareas) {
var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
for (i = 0; i < textareas; i++) {
html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
html += i;
html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
}
html += "</form>";
return html; // Return the html content with the form.
}
/*
1. Render the form with document.getElementById("div").innerHTML = buildForm(50);
2. Once the form is renderd call setPlusAction() function;
3. And call setMinusAction() function;
*/
document.getElementById("div").innerHTML = buildForm(50); // Set 50 textareas.
setPlusAction();
setMinusAction();
})();
#div div {
border: solid 1px #ccc;
margin: 2px;
padding: 2px;
}
button.plus,
button.minus {
cursor: pointer;
}
<div id="div"></div>
Update:
jQuery version:
$(function() {
// Render a form with the quantity of textareas required.
function buildForm(textareas) {
var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
for (i = 0; i < textareas; i++) {
html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
html += i;
html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
}
html += "</form>";
return html; // Return the html content with the form.
}
$("#div").html(buildForm(50)); // Render the form with 50 textareas.
$(".plus").on("click", function() {
var texarea = $(this).prev(), value = texarea.val() * 1;
value++;
texarea.val(value);
});
$(".minus").on("click", function() {
var texarea = $(this).prev().prev(), value = texarea.val() * 1;
if (value > 1) {
value--;
texarea.val(value);
}
});
});
#div div {
border: solid 1px #ccc;
margin: 2px;
padding: 2px;
}
button.plus,
button.minus {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div"></div>
Remember: IDs must be unique.
I prefer using a class, because I think it is more clear for the code.
Example: my_set_Of_Text_area.add ('<div><span> Ananas : </span>','</div>');
I prefer using data to made the link with the counting area and the + / - buttons.
$(function() {
class TxtAreaFab {
constructor(Form_ID, TextAreaPrefix, BtPlusClass, BtMinusClass) {
this._ref = 0;
this._TaP = TextAreaPrefix;
this._BtPlus = BtPlusClass;
this._BtMinus = BtMinusClass;
this._$ID = $('#' + Form_ID);
}
add(before, after) {
var elements = before;
this._ref++;
elements += "<textarea disabled id='TxtArea_" + this._ref + "'>1</textarea>";
elements += "<button class=" + this._BtPlus + " data-ref=\"TxtArea_" + this._ref + "\">+</button>";
elements += "<button class=" + this._BtMinus + " data-ref=\"TxtArea_" + this._ref + "\">-</button>";
elements += after;
$(elements).appendTo(this._$ID);
}
/* ----- not used , just here for sample
clear () {
this._$ID.html('');
this._ref = 0;
}
*/
};
var my_set_Of_Text_area = new TxtAreaFab('txtAreaForm', 'zoneTA_', 'ClassBtPlus', 'ClassBtMinus');
my_set_Of_Text_area.add('<div><span> Apples : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Oranges : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Pears : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Bananas : </span>', '</div>');
$('#txtAreaForm').on('click', "button", function(e) {
e.stopPropagation();
var $txtArea = $("#" + $(this).data("ref")),
v = parseInt($txtArea.val());
if ($(this).hasClass('ClassBtPlus')) $txtArea.val(++v);
if ((v > 1) && ($(this).hasClass('ClassBtMinus'))) $txtArea.val(--v);
return false;
});
my_set_Of_Text_area.add('<div><span> Ananas : </span>', '</div>');
});
#txtAreaForm div {
clear: both;
height: 30px;
}
#txtAreaForm div span {
display: block;
float: left;
width: 120px;
font-weight: bold;
text-align: right;
padding-right: 10px;
}
#txtAreaForm textarea {
display: block;
float: left;
width: 40px;
height: 16px;
font-weight: bold;
text-align: center;
resize: none;
}
<form name='txtAreaForm' id='txtAreaForm' method='GET'></form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Special Fun solution! (but real).
I did it with only 9 lines of JavaScript / jQuery, and a little more in CSS.
And no need for textarea id. (Ok, my 2 "if" statements have only 1 line).
For the HTML part, each text box is placed in a "p" (paragraph), and that's it:
<p><textarea disabled > 1 </textarea></p>
<p><textarea disabled > 2 </textarea></p>
<p><textarea disabled > 3 </textarea></p>
The trick is in the CSS where I use :after and :before like the "+" or "-" buttons.
placed to the right of each box "p".
form p:after {
right: -22px;
content:'+';
...
form p:before {
right: -43px;
content:'-';
In the jQuery part.
I use the relative position of the mouse click to determine whether the operation should be a plus or minus. For the little story: -- $ (this) .outerWidth (); -- Is usefull.
Of course, it would still be better to add an ID on each textarea; but after reflection, it appeared to me that these input fields could be generated at the PHP server (?).
So, strange as it may seem, this solution is very serious. ;)
Everything is in the snippet.
$(function() {
$('form p').click(function(e) {
var
posX = (e.pageX - $(this).offset().left) - $(this).outerWidth();
Sign = (posX > 22) ? "moins" : (posX > 0) ? "plus" : "none",
Valn = parseInt($(this).children('textarea').text());
if (Sign === 'plus') $(this).children('textarea').text(++Valn);
if ((Sign === 'moins') && (Valn > 1)) $(this).children('textarea').text(--Valn);
});
});
textarea,
form,
p,
textarea {
font-family: Tahoma, sans-serif;
font-size: 16px;
}
textarea {
float: left;
width: 40px;
height: 22px;
font-weight: bold;
text-align: center;
resize: none;
line-height: 20px;
}
form p {
box-sizing: border-box;
display: block;
float: left;
clear: both;
position: relative;
border: 0;
margin: 5px 0 0 20px;
padding: 0;
}
form p:before,
form p:after {
position: absolute;
top: 2px;
width: 20px;
height: 20px;
display: block;
color: white;
background-color: darkslategray;
text-align: center;
font-size: 18px;
}
form p:after {
right: -22px;
content: '+';
line-height: 18px;
}
form p:before {
right: -43px;
content: '-';
line-height: 16px;
}
<form name="txtAreaForm" method='GET'>
<p><textarea disabled> 1 </textarea></p>
<p><textarea disabled> 2 </textarea></p>
<p><textarea disabled> 3 </textarea></p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Counter not working in jQuery

I am trying to run my counter for 3 times. once I reach 3 tries the button is supposed to be disabled. I tried couple variations of this solution to no avail. the issue is right on my rollItAgain function. I have my counter starting at 3, and a for loop with an if statement inside. I am also running my randomFunction() inside my if statement, not sure if this is good practice. As of now, I only click reroll once and it gets disabled. I would like it to run at least 3 times.
// 'use strict';
var array = [];
var random = Math.ceil(Math.random() * 9);
var newStars = "<div class='star'><img src='http://i.imgur.com/kXH65I7.png'></div>";
$(document).ready(init);
function init(){
for (var i = 0; i < random; i++){
$('#starbox').append(newStars);
//Create Event Handler for selectNumbers Function
}
$('.numbers').click(selectNumbers);
$('#checked').click(confirm);
$('.numbers').click(toggleButton);
$('#playagain').click(playItAgain);
$('#reroll').click(rollItAgain);
}
function randomFunction(){
$('#starbox').empty();
random = Math.ceil(Math.random() * 9);
for (var i = 0; i < random; i++){
$('#starbox').append(newStars);
}
}
//selectNumbers function
function selectNumbers(){
var num = $(this).text();
// $(this).css('background-color', 'red');
array.push(num);
// console.log(array);
sum = array.reduce(function(a, b){
return Number(a) + Number(b);
});
console.log(sum);
//Check if numbers has select class
console.log(num);
}
function toggleButton(){
$(this).toggleClass('select');
}
function confirm(){
if (sum === random){
$('#displayResult').append("Correct!");
// $('.select').css('display', 'none');
} else {
$('#displayResult').append("Wrong, try again!!");
}
$('.select').remove();
}
function rollItAgain(){
// debugger;
var counter = 3;
// debugger;
for (var j = 0; j < counter; j++){
if(j === counter){
randomFunction();
counter++;
} else {
$('#reroll').attr('disabled', 'disabled');
}
}
}
function playItAgain(){
location.reload();
}
#numberbox {
width: 400px;
height: 100px;
border: 2px solid green ;
}
.numbers {
height: 100px;
width: 100px;
background-color:transparent;
border: 2px solid #000;
margin: 5px;
line-height: 100px;
display: inline-block;
border-radius: 50%;
text-align: center;
border: 2px solid #000;
font-size: 30px;
}
#starbox {
min-height: 300px;
min-width: 400px;
background-color:transparent;
border: 2px solid #000;
margin:100px 100px;
}
.star {
display: inline-block;
}
.select {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mathgame1</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="starbox"></div>
<p id="displayResult"></p>
<table id="numberbox" >
<button id="playagain">Play it Again</button>
<button id="checked">checked</button>
<button id="reroll">reroll</button>
<tr >
<td class="numbers">1</td>
<td class="numbers">2</td>
<td class="numbers">3</td>
</tr>
<tr >
<td class="numbers">4</td>
<td class="numbers">5</td>
<td class="numbers">6</td>
</tr>
<tr >
<td class="numbers">7</td>
<td class="numbers">8</td>
<td class="numbers">9</td>
</tr>
</table>
</body>
</html>
Ask yourself why wouldn't this code run through three times? That's what a loop does. What you're really wanting is not a loop but just a counter. The thing that triggers the rolling is the click events, not a counting loop.
First off, you are misapplying a few concepts. You have a counter variable which looks to actually represent the counter maximum. j is more appropriately called your counter. But you need to keep track of the counter value between calls to rollItAgain, so declare it outside of your function. Then increment the counter whenever rollItAgain is called. You don't have to write a loop because the clicking of the button will take care of calling the function multiple times. Secondly, change your check; you want to run the random function when the counter is less than the limit:
var counter = 0;
var limit = 3;
function rollItAgain(){
if (counter < limit) {
randomFunction();
counter++;
} else {
$('#reroll').attr('disabled', 'disabled');
}
}
The problem in your code is that you never get to condition if(j === counter){ to roll dice because your iteration only goes as far as while j < counter. So this never happens.
Rewrite your function to as below, check demo - Fiddle:
function rollItAgain() {
// debugger;
var counter = 3;
// debugger;
for (var j = 0; j <= counter; j++) {
if (j < counter) {
randomFunction();
} else {
$('#reroll').attr('disabled', 'disabled');
}
}
}

Categories

Resources