Restrict counter to be between 0 and 10 - javascript

I would like to create 2 buttons one of which increases a number and the other decreases it, and I did do it. The problem is I don't want the numbers to go higher than 10 or lower than 0, I tried if else but didn't work. Can you, please, help me?
Here is the code:
document.addEventListener("DOMContentLoaded", function () {
document.querySelector('#add').onclick = adding
document.querySelector('#minus').onclick = subtracting
})
let counter = 0
function adding() {
counter++
document.querySelector('h1').innerHTML = counter
}
function subtracting() {
counter--
document.querySelector('h1').innerHTML = counter
if( counter < 1){
document.getElementById('minus').disabled = true
} else{
document.getElementById('minus').disabled = false
}
}

I recommend you delegate and use booleans in the way they are meant
I disabled the minus on load
window.addEventListener("load", function() {
let counter = 0;
const plus = document.getElementById('plus');
const minus = document.getElementById('minus');
const result = document.querySelector('h1');
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
counter += tgt.id === "plus" ? 1 : -1; // which one did we click - this can be expanded
minus.disabled = counter < 1;
plus.disabled = counter >= 10;
result.innerHTML = counter;
})
})
<div id="container">
<button type="button" id="minus" disabled>-</button>
<h1>0</h1>
<button type="button" id="plus">+</button>
</div>

One way is
const MAX_COUNTER = 10;
const MIN_COUNTER = 0;
function adding() {
if (counter < MAX_COUNTER) {
counter++
document.querySelector('h1').innerHTML = counter
}
}
Another way is:
const MAX_COUNTER = 10;
const MIN_COUNTER = 0;
function adding() {
counter = Math.min(counter + 1, MAX_COUNTER);
document.querySelector('h1').innerHTML = counter
}
The subtracting is similar.

Your code works fine. You only need to add another if conditional for adding and put it in the adding function.
if( counter >=10){
document.getElementById('add').disabled = true
} else{
document.getElementById('add').disabled = false
}

I added a working snippet for you, you can create a common function to set the value andenable or disable button based on counter values.
var counter = 0;
document.addEventListener("DOMContentLoaded", function() {
//initial value
setCounterValue(counter);
//add function
document.querySelector('#add').onclick = function() {
setCounterValue(++counter); //increase the counter
}
//substract function
document.querySelector('#minus').onclick = function() {
setCounterValue(--counter); //decrease the counter
}
});
//set the value and enable or disable buttons
function setCounterValue(value) {
document.querySelector('h1').innerHTML = value;
document.getElementById('minus').disabled = (value <= 0);
document.getElementById('add').disabled = (value >= 10);
}
<p> Counter </p>
<h1 id="h1"> </h1>
<button id="add">Add</button> <button id="minus">Substract</button>

Related

Scann the value of an span and add an counter in another div when the value is 0 or less

Im trying to scann the value of an span element, by clicking an button. And if the value of the span is 0 the counter in the div is supposed to add one.
Here is a part of the HTML i use:
<span id="result"></span>
<button id="calculateBtn">Calculate</button>
<div id="playerlegs"></div>
I already tried something out with JS but nothing happens and i don't now why and what could also work.
const button = document.querySelector("#calculateBtn");
const spanElement = document.querySelector("#result");
const displayElement = document.querySelector("#playerlegs");
let count = 0;
button.addEventListener("click", function() {
const spanValue = parseInt(spanElement.textContent, 10);
if (spanValue === 0) {
count++;
displayElement.innerHTML = count;
} else if (spanValue < 0) {
displayElement.innerHTML = "Negative number";
}
});

Make steps in the incremental values with a button

I made this code that increments a number with a button. I would like to add a condition when the number reaches a defined value, in order to display a text. Thanks for the help.
My code:
const incrementCount = document.getElementById("btn");
const totalCount = document.getElementById("compteur");
var count = 0;
totalCount.innerHTML = count;
const handleIncrement = () => {
count++;
totalCount.innerHTML = count;
};
incrementCount.addEventListener("click", handleIncrement);
<div id="compteur"></div>
<div id="btn" ontouchstart ontouchend></div>
Just have a maxCount variable and compare the new count to the max after each iteration. Once the max is reached, a message will display.
In the example below, the count will keep going. The alert is wrapped in a setTimeout so that the count can be updated to 10, before the alert dialog is displayed.
const
incrCountBtn = document.querySelector('#btn'),
totalCountEl = document.querySelector('#compteur'),
maxCount = 10,
message = 'You have reached the limit';
let count = 0;
totalCountEl.innerText = count;
const handleIncrement = () => {
count += 1;
totalCountEl.innerText = count;
if (count === maxCount) {
setTimeout(() => {
alert(message);
}, 100);
}
};
incrCountBtn.addEventListener('click', handleIncrement);
<div id="compteur"></div>
<button type="button" id="btn" ontouchstart ontouchend>Increment</button>

I am trying to increment when increment button is pressed but I am getting [object HTMLParagraphElement]1

I am working on this increment function when the increment button is pressed that should add +1 to count element.
This is my html:
<p id="count-el">0</p>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
JS:
let countEl = document.getElementById('count-el');
function increment() {
countEl.textContent = countEl + 1;
}
You need to create a variable and then increment that variable in your increment function.
let count = 0;
let countEl = document.getElementById('count-el');
countEl.textContent = count;
function increment() {
count++;
countEl.textContent = count;
}
You can either use a 'count' variable to maintain count and display it after every increment.
Or parse the number in the inner text to int and add.
This should work:
let countEl = document.getElementById('count-el');
function increment() {
countEl.textContent = parseInt(countEl.innerHTML) + 1;
}
Try this
let countEl = document.getElementById('count-el');
let count = 0;
function increment() {
count++;
countEl.textContent = count;
}
function decrement() {
count--;
countEl.textContent = count;
}
<p id="count-el">0</p>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
<button id="increment-btn" onclick="decrement()">DECREMENT</button>
It is widely considered bad practice to use inline event listeners. Instead, use EventTarget.prototype.addEventListener like this:
const countEl = document.getElementById('count-el');
const incrementBtn = document.getElementById('increment-btn');
const decrementBtn = document.getElementById('decrement-btn');
function increment() {
countEl.textContent = Number(countEl.textContent) + 1;
}
function decrement() {
countEl.textContent = Number(countEl.textContent) - 1;
}
incrementBtn.addEventListener('click', increment);
decrementBtn.addEventListener('click', decrement);
countEl.textContent = 0;
<p id="count-el"></p>
<button type="button" id="increment-btn">+</button>
<button type="button" id="decrement-btn">-</button>
Since you have the counter value in your element, you do not need to maintain it globally.
function increment() {
const countEl = document.getElementById('count-el');
// Validates the current counter value, Defaults to 0
const count = parseInt(countEl.textContent) || 0;
countEl.textContent = count + 1;
}

Trying to set up code when it reaches a certain number , the button becomes disable and can go no futher

THIS IS MINE JAVASCRIPT
I'm having trouble figuring out a way to disable the button feature. When it reaches a certain number.
let counter = document.getElementById("counter");
let add = document.querySelector(".add");
let minus = document.querySelector(".minus");
let count = 0;
>add.addEventListener("click", () => {
>>count ++;
>>>counter.innerHTML = count;
>if (count > 10) {
return;
}
});
>minus.addEventListener("click" , () =>{
>>count --;
>>>counter.innerHTML = count;
});
You can disable the button with add.setAttribute('disabled', 'true'):
let counter = document.getElementById("counter");
let add = document.querySelector(".add");
let minus = document.querySelector(".minus");
let count = 0;
add.addEventListener("click", () => {
count++;
counter.innerHTML = count;
if (count >= 10) {
add.setAttribute('disabled', 'true');
}
});
minus.addEventListener("click", () => {
count--;
counter.innerHTML = count;
});
<p id="counter">0</p>
<button class="add">+</button>
<button class="minus">-</button>
This will show you how you can manage the disabling/enabling of the buttons according to count. I have created a single event listener that gets applied to both buttons and is able to determine if it's the plus or minus that was clicked. I moved the disabling stuff into it's own function since we need to call it on page load as well as in the button listeners. This also has the benefit of having a max and min set of values you can disable on. Plus, it's dynamic, so if you go up to 10 it will disable, but if you minus, it will re-enable, if that makes sense.
let counter = document.getElementById("counter");
let mathButton = document.querySelectorAll(".math");
let count = 0;
let max = 10,
min = 0
window.addEventListener('load', () => {
counter.innerHTML = count
manageButtons()
mathButton.forEach(m => {
m.addEventListener("click", (e) => {
let inc = e.target.classList.contains('minus') ? -1 : 1;
mathButton.forEach(b => b.removeAttribute('disabled'));
counter.innerHTML = count;
manageButtons()
count += inc;
});
});
});
function manageButtons() {
if (count >= max) document.querySelector(".add").setAttribute('disabled', 'disabled');
if (count <= min) document.querySelector(".minus").setAttribute('disabled', 'disabled');
}
<div id='counter'></div>
<button class='math add'>+</button> <button class='math minus'>-</button>

can't access value through input using button

I'm doing some exercises and come across where I can't pass the value from the input box to a function inside a script, I don't really know what I have done wrong, I tried different things but didn't really work out. How can I make it work? I want to able to enter a number then press a button so that it prints pyramid according to given number, here is my code :
window.onload = function() {
let aantalLijnen = parseInt(document.getElementById('number').value);
document.getElementById("button").onclick = stars();
function stars() {
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
You're calling stars() and assigning the result to the onclick handler.
You need to pass the function itself...
document.getElementById("button").onclick = stars;
Or just create an anonymous function directly...
document.getElementById("button").onclick = function() {
...
}
As pointed out by #j08691, you are setting the value of aantalLijnen on the page load.
Instead you want to get the value at the time the function runs, so you need to move it into the function itself...
window.onload = function() {
document.getElementById("button").onclick = function () {
let aantalLijnen = parseInt(document.getElementById('number').value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
you have to get the value from input every time you click on the button
window.onload = function () {
const numberElem = document.getElementById('number');
document.getElementById("button").addEventListener('click', stars);
function stars() {
let aantalLijnen = parseInt(numberElem.value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
Besides what already said by others
Don't use onclick handlers. Stick to cumulative listeners with addEventListener
You could use String.prototype.repeat();
Defer your script or place it right before the closing </body> tag
Learn the difference between let and const
function stars() {
const num = parseInt(document.getElementById('number').value, 10);
if (num < 2 || num > 10) return console.log("Use from 2 to 10 inclusive");
const row = '*'.repeat(num);
console.log(row)
}
document.getElementById("button").addEventListener('click', stars);
Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button>

Categories

Resources