One function for two buttons (increment, decrement) - javascript

I want to be able to increment and also decrement a value (5) and I would like to cover this with one function (I know how to do it with two).
Unfortunately I am not able to get it done and can't figure out what is wrong.
Here is my code:
HTML:
<form>
<button type="button" value="minus" onclick="updateAmount();">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount();">
+
</button>
</form>
JS:
var num = parseInt(document.getElementById('number');
var btn = document.querySelector('button');
btn.addEventListener('click', updateAmount);
function updateAmount(){
btn.value === "minus" ? num-- : num++;
document.getElementById('number').value = num;
}
Also at JSfiddle
I would prefer a vanilla JS solution if possible, but any suggestion is welcome :)
Thanks!

The minimal-changes to your approach is to pass an argument to the function:
function updateAmount(value) {
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(-1);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(1);">
+
</button>
</form>
Or use your value attribute and pass this into the function:
function updateAmount(btn) {
var value = btn.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
That latter approach combines nicely with modern event handling:
// Scoping function so our `updateAmount` isn't global
(function() {
document.querySelector("button[value=minus]").addEventListener("click", updateAmount);
document.querySelector("button[value=plus]").addEventListener("click", updateAmount);
function updateAmount() {
var value = this.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
})();
<form>
<button type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus">
+
</button>
</form>

You could hand over the action as a parameter
<form>
<button type="button" value="minus" onclick="updateAmount('minus');">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount('plus');">
+
</button>
</form>
and then
function updateAmount(action) {
var num = parseInt(document.getElementById("number").innerHTML, 10);
switch(action) {
case 'minus':
num--;
break;
case 'plus':
num++;
break;
}
document.getElementById("number").innerHTML = num;
}

You can try this ...
<html>
<form>
<button type="button" value="minus" onclick="updateAmount(this.value);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this.value);">
+
</button>
</form>
<script>
function updateAmount(value){
var num = parseInt(document.getElementById('number').innerHTML);
value=='plus'?num++:num--;
document.getElementById('number').innerHTML = num;
}
</script>
</html>

You were close, as you have multiple elements use document.querySelectorAll() with valid selector to get there reference and bind event handlers.
As you are using <SPAN> element, it doesn't have value property, need to use textContent property.
var btns = document.querySelectorAll('button');
btns.forEach(function(btn) {
btn.addEventListener('click', updateAmount);
});
function updateAmount() {
var num = parseInt(document.getElementById('number').textContent.trim(), 10);
this.value === "minus" ? num-- : num++;
document.getElementById('number').textContent = num;
}
<button type="button" value="minus">-</button>
<span id="number">5</span>
<button type="button" value="plus">+</button>
Note: Get rid of ugly inline click handlers.

simply use like this updateAmount(this)
function updateAmount(that) {
var number = document.getElementById('number');
var num = parseInt(number.innerHTML);
num = (that.value == "minus") ? --num : ++num;
number.innerHTML = num;
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>

var minusBtn = document.querySelector('#minus');
var plusBtn = document.querySelector('#plus');
minusBtn.addEventListener('click', updateAmount('minus'));
plusBtn.addEventListener('click', updateAmount('plus'));
function updateAmount(action) {
return function() {
var numberElem = document.getElementById('number');
var number = numberElem.innerText;
number = parseInt(number, 10);
if (action === 'minus') {
number--;
} else if(action === 'plus') {
number++;
} else {
throw new Error('invalid operator');
}
numberElem.innerText = number;
};
}
<form>
<button id = "minus" type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button id = "plus" type="button" value="plus">
+
</button>
</form>
this is a good example for curry function, you can currify your updateAmount to accept action as a part of argument

Your code has just two small flaw, rest is perfect.
Firstly Your variable num is evaluating to NaN.
Secondly you should use textContent instead of value .
I am sharing correct way to evaluate num and then it will work.
var el =document.getElementById('number')
var num = parseInt(el.textContent);
Again, while updating
document.getElementById('number').textContent = num
Hope it helped.

Related

How to set minimum Increment ++ and Decrement -- value (can't go bellow 1) + how to decrease or increase button added value

I am working on a web store which offers 2 pre-assigned options (buy two for XX and buy 3 for XY). I also added a normal - 0 + system whith which the customer can select a different number of products.
I wrote a little code which works fine for +- or 2,3 alone, but if i wanna decrease a number added by 2,3 buttons, it doesn't go from 3 to 2 but to 0 or -1.
So, i want to be able to select pre-defined option 2 or 3 but i also want it to be editable by +- buttons.
Any suggestions?
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="0"></input>
<button class="plus" onclick="buttonClicDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
i++;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
var i = 0;
function buttonClickDOWN() {
i--;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
</script>
As I already mention in the comment, you have a typo in buttonClicDOWN .......missing k. You directly increment/decrement the value of the element. Please see the modified functions:
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
I'd have this added as a comment, but was not able to for missing rep. So an answer:
In simple terms: you are not updating your global variable i when pressing the 2 or 3 button, so when you in/decrease i and assign it to the value property, you do override the old value.
I would recommend to drop the i (global) variable and just to work with the value property, e.g.
function buttonClickDOWN() {
var elm = document.getElementById('gumb2');
if (elm.value > 0)
elm.value--;
else
elm.value = 0;
}
P.S.: as you are using a text type input, you might also want to consider non-numbers the user might have entered.
Why not simply use input type="number"?
<button class="gumb_shop2" onclick="gumb2.value=2">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="gumb2.value=3">3 for 8,99 €</button>
<input type="number" id="gumb2" value="1" step="1" min="1" />
<input type="button" id="order" value="ORDER NOW" />
Here's a simple example that that meets your specs:
<button onclick="setAbs(event)" data-val="2">2 for 10,99 €</button>
<button onclick="setAbs(event)" data-val="3">3 for 8,99 €</button><br/><br/>
<button onclick="down()">-</button>
<input size="2" id="counter" value="0" />
<button onclick="up()">+</button><br/><br/>
<input type="submit" value="Submit" />
<script>
let counter = document.getElementById("counter");
function setAbs(event){
counter.value = event.target.dataset.val;
}
function up(){
counter.value = parseInt(counter.value) + 1;
}
function down(){
if(counter.value > 0){
counter.value = parseInt(counter.value) - 1;
}
}
</script>
this is the answer i was looking for.
Thank you #Mamun for quick response.
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>

jQuery multiple plus/minus Counter

I want to have multiple plus/minus counters on my page.
I have one working counter but want to make it generic so that multiple counters can have a different initial value and increase and decrease as clicked.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('.output').html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
<hr />
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
Fiddle Link:
http://jsfiddle.net/u2Lh7dbp/
Thanks
Each output element should be unique so it can be called by itself.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('#output-' + $btn.data('index')).html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-index="1" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-index="1" data-inc="-1">-</button>
<div class="output" id="output-1">+30</div>
<hr />
<button class="counter-btn" id="increase2" type="button" data-index="2" data-inc="1">+</button>
<button class="counter-btn" id="decrease2" type="button" data-index="2" data-inc="-1">-</button>
<div class="output" id="output-2">+30</div>
I've added a new data attribute: index. You can use that index to specify the exact output element you're looking for by its id.
Keeping it simple, you can have two functions and directly associate the onClick callback to these functions, making it more clear on the html side.
function add(id) {
var newCount = parseInt($(id).text()) + 1;
$(id).text(newCount);
}
function substract(id) {
var newCount = parseInt($(id).text()) - 1;
$(id).text(newCount);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="add('#output1')">+</button>
<button type="button" onclick="substract('#output1')">-</button>
<div id="output1">30</div>
<hr />
<button type="button" onclick="add('#output2')">+</button>
<button type="button" onclick="substract('#output2')">-</button>
<div id="output2">30</div>

Get the value of incremented input

I have two buttons which either increment or decrement an input value. I don't know how to retrieve the value later on submit of the result. My current attempts have either resulted in 'undefined' or '0'.
Thanks in advance for any advice
$('.plus').click(function(e){
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal)) {
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
$(".minus").click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal) && currentVal > 0) {
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
//attempting to get value
var value = document.getElementById( 'inputval' ).val();
$('#submitscore').click(function() {
alert(value);
});
My HTML
<span class="input-group-btn">
<button class="btn btn-secondary btn-success minus" field='minusfield' id ="minus" type="button">-</button>
</span>
<input type="text" name="inputval" id="inputval" value="0" class="gh form-control" />
<span class="input-group-btn">
<button class="btn btn-secondary btn-success plus" id="plus" field='plusfield' type="button">+</button>
</span>
<button type="button" id="submitscore" class="btn btn-md btn-orange">Submit</button>
You are attempting to get already assigned value.
Change your code to this
$('#submitscore').click(function() {
alert($('#inputval').val());
});
and it should work.
You're mixing standard Javascript usage with jQuery usage when you try to call it like this:
//attempting to get value
var value = document.getElementById( 'inputval' ).val();
Use one or the other:
Standard Javascript:
document.getElementById('inputval').value
jQuery:
$('#inputval').val()

How do I create addition function in javascript from one input box

I'm trying to make JavaScript calculator. I want to create simple addition function in JavaScript but didn't know how to build that logic, need someone help, and in my code one input text field is present.
Code contain input buttons which is numbers now I need help. So how do I do addition function in JavaScript?
function plus()
{
var textInputval=0;
var textInputval1=2;
var temp=0;
textInputval = parseInt(document.getElementById('new').value);
textInputval1 = parseInt(document.getElementById('new').value);
temp = textInputval + textInputval1;
console.log(textInputval);
console.log(textInputval1);
}
<div id = "cal-container">
<form name="calculator">
<input type="text" name="answer" value="" id="new">
<br>
<input type="button" value=" 1 " onclick="one()" />
<input type="button" value=" 2 " onclick="two()" />
<input type="button" value=" 3 " onclick="three()" />
<input type="button" value=" + " onclick="plus()" />
</form>
</div>
function action(method) {
var a = parseInt(document.getElementById("num1").value);
var b = parseInt(document.getElementById("num2").value);
var result = null;
switch (method) {
case 'add':
result = a + b;
break;
case 'subtract':
result = a - b;
break;
case 'multiply':
result = a * b;
break;
case 'divide':
if (b != 0) {
result = a / b;
} else {
alert('Can\'t divide by 0');
return;
}
break;
}
if (result !== null) {
document.getElementById("result").value = result;
} else {
document.getElementById("num1").value = "";
document.getElementById("num2").value = "";
document.getElementById("result").value = "";
}
}
<span style="margin-right:1px">Number 1 </span>
<input id="num1" type="number"></br>
<span style="margin-right:5px">Number 2</span><input id="num2" type="number"></br>
<span style="margin-right:29px">Result</span><input id="result" type="number"> </br>
<button id="add" onclick="action('add')">+</button>
<button id="subtract" onclick="action('subtract')">-</button>
<button id="multiply" onclick="action('multiply')">*</button>
<button id="divide" onclick="action('divide')">/</button>
<button id="clear" onclick="action('clear')">clear</button>

jQuery increment or decrement variable by 1

I have simple plus and minus button on either side of input field as in the code below
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%" onclick="subst()" />
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="<?php echo set_value('noOfRoom'); ?>" name="noOfRoom" />
<input type="button" value="+" id="adds" onclick="add()" class="btn btn-default" />
with aim to add or subtract rooms while adding rooms and the jquery functions as
function add() {
var a = $("#noOfRoom").val();
a++;
if (a => 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
but the following problems are shown
when i click on subtract (-) button at the initial phase -1 is shown in input box, where by default the subtract (-) button should be disabled to make rooms number negative.
Each time when I click on PLUS or MINUS buttons the numbers are added or subtracted by 2. How could I solve it?
Update add a fiddle https://fiddle.jshell.net/n7ug52dr/
Each time you click will only add and sub by 1, and it never show the -1
You can edit code like this:
function add() {
var a = $("#noOfRoom").val();
a++;
if (a && a >= 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
// this is wrong part
if (b && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
Moving comments to answer as no-one took onboard the suggestions:
I suggest not using inline onclick= handlers with jQuery. They separate the event handler from the event code for no reason and don't allow for the extra features of jQuery event handlers.
Use prop and not attr for DOM element properties (like disabled). This has the extra advantage of taking a boolean value.
You can then simply use !a to control the disabled state (as you are only checking for 0).
As a good habit always select DOM elements once and save the selector.
e.g.
$('#adds').click(function add() {
var $rooms = $("#noOfRoom");
var a = $rooms.val();
a++;
$("#subs").prop("disabled", !a);
$rooms.val(a);
});
// Set initial disabled state
$("#subs").prop("disabled", !$("#noOfRoom").val());
$('#subs').click(function subst() {
var $rooms = $("#noOfRoom");
var b = $rooms.val();
if (b >= 1) {
b--;
$rooms.val(b);
}
else {
$("#subs").prop("disabled", true);
}
});
JSFiddle: https://jsfiddle.net/k7nyv84b/4/
Here you go, champ! Made your code a little cleaner as well
See the working example below
$(function(){
$('#adds').on('click',add);
$('#subs').on('click',remove);
});
function add(){
var input = $('#noOfRoom'),
value = input.val();
input.val(++value);
if(value > 0){
$('#subs').removeAttr('disabled');
}
}
function remove(){
var input = $('#noOfRoom'),
value = input.val();
if(value > 0){
input.val(--value);
}else{
$('#subs').attr('disabled','disabled');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%"/>
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="0" name="noOfRoom" />
<input type="button" value="+" id="adds" class="btn btn-default" />
take a look at this solution
<input type="button" value="-" id="subs" onclick="subst()" disabled>
<input type="text" id="noOfRoom">
<input type="button" value="+" id="adds" onclick="add()">
function add() {
var a = $("#noOfRoom").val();
a++;
if (a >= 1) {
$("#subs").removeAttr("disabled");
}
alert(a);
$("#noOfRoom").val(a);
}
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
alert(b);
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
//alert('works well');
}
The simplest way is to use DOM to navigate through elements and get its current value and then increase/decrease them.
I extended the code to make sure when minus button is clicked value isn't reduce below zero.
<input type="button" value="-" class="qtyminus" field="quantity">
<input type="number" class="input-lg" id="quantity" name="quantity" value="1" min="1" style="padding:0px;height:30px;">
<input type="button" value="+" class="qtyplus" field="quantity">
<input type="submit" name="add" id="add" class="btn btn-large btn-border btn-dark" value="GET IT NOW" style="opacity: 1;">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
<button onClick="myfun()">+</button>
<!--<button onClick="myfun()" id="pluse">+</button>-->
<input type="text" id="pluse" >
<button onClick="myfun1()">_</button>
var a = 0;
function myfun(){
a++;
document.getElementById('pluse').value = a;
//document.getElementById('pluse').innerHTML = a;
}
function myfun1(){
a--;
document.getElementById('pluse').value = a;
}

Categories

Resources