Can you use decrement/increment operator but skip 0 in JavaScript just like how continue works? - javascript

I have here a number counter code where it has increment and decrement buttons. Whenever you click a button, it does its job of incrementing and decrementing the value of the input.
// =number_counter
function decrement(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value--;
target.value = value;
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
function increment(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value++;
target.value = value;
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
const decrementButtons = document.querySelectorAll(
`button[data-action="decrement"]`
);
const incrementButtons = document.querySelectorAll(
`button[data-action="increment"]`
);
decrementButtons.forEach(btn => {
btn.addEventListener("click", decrement);
});
incrementButtons.forEach(btn => {
btn.addEventListener("click", increment);
});
This time, I wanted to skip 0 when clicking the buttons having the input value as either -1 or 1. Can I add a behavior such as continue; without the loop and just having increment/decrement operators?

Continue does't exist outside of the loops. The simplest solution for you is to add a condition inside increment/decrement where you would check if the current value is -1/1 and add additional logic in those cases :)

The solution was just to set the value = 1 or value = -1;
function decrement(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value--;
if (value == 0) {
value = -1;
target.value = value;
} else {
target.value = value;
}
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
function increment(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value++;
if (value == 0) {
value = 1;
target.value = value;
} else {
target.value = value;
}
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
Sorry I have missed it.

Related

Get a result when an option value selection is changed in javascript

I'm trying to get a different value when the value of an option is changed. I have this code, but when I change my selection, the result is not changing.
let cantidad1 = document.getElementById("cantidad");
let moneda1 = document.getElementById("cambio").value;
if (moneda1 === "cup") {
tipodemoneda = 97;
} else if (moneda1 === "mlc") {
tipodemoneda = 0.89;
}
let tasadecambio = tipodemoneda;
let resultado1 = document.getElementById("resultado")
cantidad1.addEventListener("change", () => {
resultado1.value = parseFloat(tasadecambio) * parseFloat(cantidad1.value)
})
Listen for input events instead of change events. Change events only fire for a text input or text area when the the element lose focus (1)
let cantidad1 = document.getElementById("cantidad");
let moneda1 = document.getElementById("cambio").value;
if (moneda1 === "cup") {
tipodemoneda = 97;
} else if (moneda1 === "mlc") {
tipodemoneda = 0.89;
}
let tasadecambio = tipodemoneda;
let resultado1 = document.getElementById("resultado")
cantidad1.addEventListener("input", () => {
resultado1.value = parseFloat(tasadecambio) * parseFloat(cantidad1.value)
})
<input id="cantidad">
<input id="cambio" value="cup">
<input id="resultado">
Also the way the code is right now, moneda1 only gets set once. You should move it into the event handler.
let cantidad1 = document.getElementById("cantidad");
let moneda1 = document.getElementById("cambio");
let resultado1 = document.getElementById("resultado")
let tipodemoneda; // Put this to stop it from being a global variable (window.tipodemoneda)
function updateResultado() { // Handler in its own function
if (moneda1.value === "cup") { // Check mondedal.value since it can change
tipodemoneda = 97;
} else if (moneda1.value === "mlc") {
tipodemoneda = 0.89;
}
let tasadecambio = tipodemoneda;
resultado1.value = parseFloat(tasadecambio) * parseFloat(cantidad1.value)
}
cantidad1.addEventListener("input", updateResultado)
moneda1.addEventListener("change", updateResultado)
<input id="cantidad">
<select id="cambio">
<option value="mlc">mlc</option>
<option value="cup">cup</option>
</select>
<input id="resultado">

I want to prevent being able to choose a number less than zero with e.target.value

I want to prevent negative values ( < 0) to be chosen on input field. Being "0" the lowest value available for the input field.
Here is the javascript and html code:
// Button functions
const minusButton = document.getElementById('minus');
const plusButton = document.getElementById('plus');
const inputField = document.getElementById('amount');
minusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue - 0.01;
});
plusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue + 0.01;
});
// Returning 0 when clearing input
const numInputs = document.querySelectorAll('input[type=number]')
numInputs.forEach(function(input) {
input.addEventListener('change', function(e) {
if (e.target.value == '') {
e.target.value = 0
}
})
})
<button class="input-btn" id="minus">−</button>
<button class="input-btn" id="plus">+</button>
<input class="input" type="number" value="0" id="amount"/>
Your code is almost correct.
In the minusButton event handler logic, you can enforce that the value never gets set to anything lower than 0.
Edit the input event handler to check for values lower than 0, not equal to it.
Note: the event handler you add to input to fire upon 'change' only gets executed when the user manually makes the change to the value of input box, and NOT when it gets changed by code (as you're doing through minusButton and plusButton). Since, the user clicks the button (and never interact with the input directly), the event happens on the button, not the input box.
You can give below code a try.
// Button functions
const minusButton = document.getElementById("minus");
const plusButton = document.getElementById("plus");
const inputField = document.getElementById("amount");
minusButton.addEventListener("click", (event) => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
// if less than 0, set to 0, else currentValue - 0.01
inputField.value = currentValue - 0.01 < 0 ? 0 : currentValue - 0.01;
});
plusButton.addEventListener("click", (event) => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue + 0.01;
});
// Returning 0 when clearing input
const numInputs = document.querySelectorAll('input[type="number"]');
numInputs.forEach((input) => {
input.addEventListener("change", function (e) {
if (e.target.value === "" || e.target.value < 0) {
e.target.value = 0;
}
});
});
If you were using a submit button and the input box was in a form element, you could have used the min attribute
<input class="input" type="number" value="0" id="amount" min="0" />
This would be the ideal front-end way of doing it.
You could use JavaScript too, but it can be disabled by the user.
You should, however, check this value (validation) when it gets submitted, before you use it because even this can be bypassed.
let newValue = currentValue - 0.01
if(newValue < 0) {
newValue = 0
}
inputField.value = newValue

how to decrease or increase a number bu pressing the button Java script

Hey guys i've made buttons of '+' and '-' and there is a number which i need to increase or decrease while pressing the + or -, here my code but it isn't working. Will be glad if you can help me.
thank you!
button class="plus_minus"></button><span class="number">1</span><button class="minus_plus"></button>
my JS
const plus = document.querySelector('.plus_minus'),minus = document.querySelector('.minus_plus');
let number = parseInt(document.querySelector('.number'));
plus.addEventListener('click',() => {number++ ;});
minus.addEventListener('click',() => {number--;
});
Anyway, I would suggest this:
HTML :
<button class="minus">-</button><span id="number">1</span><button class="plus">+</button>
One class for "minus" button and one class for "plus" button. In your code you didn't differenciate them.
JS:
const minus = document.querySelector('.minus')
const plus = document.querySelector('.plus');
plus.addEventListener('click',() => document.getElementById("number").textContent++);
minus.addEventListener('click',() => document.getElementById("number").textContent--);
Add two listeners that directly increment/decrement the value.
I updated your code and it will help you.
let number = parseInt(document.querySelector('.number'));
document.querySelector('.number') returns element with "number" classname , not it's content text.
document.querySelector('.number').innerText returns the element's content text.
let oldVal = 1;
let newVal = oldVal++;
// output: newVal = 1 oldVal = 2
let oldVal = 1;
let newVal = ++oldVal;
// output: newVal = 2 oldVal = 2
const plus = document.querySelector('.plus_minus'),
minus = document.querySelector('.minus_plus');
let number_el = document.querySelector('.number');
plus.addEventListener('click', () => {
let val = parseInt(number_el.innerText);
number_el.innerText = ++val;
});
minus.addEventListener('click', () => {
let val = parseInt(number_el.innerText);
number_el.innerText = --val;
});
<button class="plus_minus">+</button>
<span class="number">1</span>
<button class="minus_plus">-</button>
Right now you number variable is reference of the span element.
You should get the value (innerHTML) of that
let number = parseInt(document.querySelector('.number').innerHTML);
In the event listener you should update the DOM (innertHTML of span) again after the value is updated.
plus.addEventListener('click',() => {
number++ ;
document.querySelector('.number').innerHTML = number;
});
minus.addEventListener('click',() => {
number--;
document.querySelector('.number').innerHTML = number;
});

How can I reset counter to 0 if value from function parameter is different in JavaScript?

I am sending value dynamically in counter function i.e, button can be counter(0), counter(1),counter(2), etc.
Now say if count = 0 (i.e, counter(0)), then I want to increment global variable i.
And now count = 1, then reset the global variable i to 0 and again start incrementing from first.
Again, say if button counter is 0 again and for counter 0 last increment was 4, then it must start from 5.
How can I do that in javascript. Is it possible to do so?
var i =0;
function counter(count){
i++;
}
<button type="button" onclick=counter(0)>Change counter</button>
var count = 0;
function myfunction() {
<button type="button" onclick="counter(` + count + `)" class="btn btn-primary rounded-0 float-right">Change Counter</button>
count++;
}
You need a separate counter for each number. You can't do this with a single global. Otherwise it resets when you change the button you click and you can never get the old value back when you go back to the previous button.
Use an object to store the counters in.
If you need to have a global value with the latest value of the most recently manipulated counter, copy the value to it afterwards.
let lastCounterValue = 0;
const counters = {};
const increment = event => {
const button = event.currentTarget;
const counterId = button.textContent;
if (!(counterId in counters)) {
counters[counterId] = 0;
}
counters[counterId]++;
lastCounterValue = counters[counterId];
console.log({
lastCounterValue,
counters
});
}
document.querySelectorAll("button").forEach(button => button.addEventListener("click", increment));
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
I would keep an array for each button with an unique identifier.
HTML
<button type="button" onclick="counter('a', 0)">Change counter</button>
<button type="button" onclick="counter('b', 3)"">Change counter</button>
JS
var clickArr = {};
function counter(id, count){
clickArr[id] = !isNaN(clickArr[id]) ? (clickArr[id]+1) : count;
console.log(clickArr);
}
var i = 0;
function cal() {
let cache = 0;
return function(count) {
if (count == 0) {
if (i == 0) {
i = ++cache;
// use memoized val
} else {
i++;
cache = i;
// increment
}
} else if (count == 1) {
/*set to 0, don't update cache now,
wait for next input */
i = 0;
} else {
i = count;
cache = count;
}
}
}
var counter = cal();
counter(0)
counter(0)
counter(0)
console.log('3', i)
counter(99)
console.log('99', i)
counter(1)
counter(0)
console.log('100', i)

Prevent user to type more than one decimal dot in a JS calculator

In my calculator project with Javascript I'm trying to prevent a user to input multiple decimal points if there is one already (example : 5.2.3.56 not allowed).
All the numbers, decimal and operator buttons that the user clicks on are pushed and stored in an array.
How can I check if there is a dot already and disable the button using an array of values?
const numButtons = document.querySelectorAll('.number');
const opButtons = document.querySelectorAll('.operation');
const display = document.querySelector('.display');
const decimal = document.querySelector('.decimal');
let opClicked;
let resultArray = [];
// Event listeners
numButtons.forEach(number => {
number.addEventListener('click', function(e) {
numClicked = e.target.textContent;
if (display.textContent === '0') {
display.textContent = '';
} else if (resultArray[resultArray.length - 1] === opClicked){
display.textContent = '';
}
resultArray.push(numClicked);
display.textContent += numClicked
});
opButtons.forEach(operator => {
operator.addEventListener('click', function(e) {
empty();
opClicked = e.target.textContent;
resultArray.push(opClicked);
operate();
});
decimal.addEventListener('click', function(e) {
let decimalClicked = e.target.textContent;
resultArray.push(decimalClicked);
display.textContent += decimalClicked;
});
decimal.addEventListener('click', function(e) {
var decimalClicked = e.target.textContent;
if(resultArray.includes(decimalClicked) == false){
resultArray.push(decimalClicked);
display.textContent += decimalClicked;
}
});
The code above checks the resultArray to see if it contains a decimal, if it does not, then it appends the decimal to the array

Categories