Change just one input field with javascript - javascript

I have code like this:
<script>
(function() {
window.inputNumber = function(el) {
var min = el.attr('min') || false;
var max = el.attr('max') || false;
var els = {};
els.dec = el.prev();
els.inc = el.next();
el.each(function() {
init($(this));
});
function init(el) {
els.dec.on('click', decrement);
els.inc.on('click', increment);
function decrement() {
var value = el[0].value;
value--;
(value<1) ? value=1 : '';
if(!min || value >= min) {
el[0].value = value;
}
}
function increment() {
var value = el[0].value;
value++;
if(!max || value <= max) {
el[0].value = value++;
}
}
}
};
})();
inputNumber($('.input-number'));
</script>
but this will change every input field when I click on one decrement or increment... But I need to be separated and dynamic, here is html:
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left"></i></span><input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right"></i></span>
</div>
I can have more then one input field, and all need to work separately... Any solution?

The problem is here
els.dec = el.prev();
els.inc = el.next();
.prev() and .next() will get all the preceding and following elements of the matched elements in el.
Remove this step completely and use
function init(el) {
el.prev().on('click', decrement);
el.next().on('click', increment);
// ...
instead.
(function() {
window.inputNumber = function(el) {
var min = el.attr('min') || false;
var max = el.attr('max') || false;
el.each(function() {
init($(this));
});
function init(el) {
el.prev().on('click', decrement);
el.next().on('click', increment);
function decrement() {
var value = el[0].value;
value--;
(value < 1) ? value = 1: '';
if (!min || value >= min) {
el[0].value = value;
}
}
function increment() {
var value = el[0].value;
value++;
if (!max || value <= max) {
el[0].value = value++;
}
}
}
};
})();
inputNumber($('.input-number'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left">-</i></span>
<input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right">+</i></span>
</div>
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left">-</i></span>
<input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right">+</i></span>
</div>
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left">-</i></span>
<input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right">+</i></span>
</div>

You should initialize your code like that:
$('.input-number').each(function(){
inputNumber($(this));
})
instead of:
inputNumber($('.input-number'));
See JS fiddle

Related

Increment/Decrement Counter for 3 Buttons?

I have three buttons like this on my site:
I'm trying to increment and decrement the counters but it's only working for two, the first works fine but the second is adding 2 to every increment and the third isn't working at all.
Here is the code:
$('.plus').on('click', function(e) {
var val = parseInt($(this).prev('input').val());
$(this).prev('input').val(val + 1);
console.log(val);
});
$('.minus').on('click', function(e) {
var val = parseInt($(this).next('input').val());
if (val !== 0) {
$(this).next('input').val(val - 1);
}
if (val == 0) {
$(this).next('input').val(1);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="quantitiy" for="Quantity-collection-template-new"></label>
<input class="minus minus1" type="button" value="-">
<input type="number" id="Quantity-collection-template-new" name="quantity" value="1" min="1" class="product-form__input qty" pattern="[0-9]*" data-quantity-input="">
<input class="plus plus1" type="button" value="+">
<label class="quantitiy" for="Quantity-collection-template-new"></label>
<input class="minus minus2" type="button" value="-">
<input type="number" id="Quantity-collection-template-new" name="quantity" value="1" min="1" class="product-form__input qty" pattern="[0-9]*" data-quantity-input="">
<input class="plus plus2" type="button" value="+">
<label class="quantitiy" for="Quantity-collection-template-new"></label>
<input class="minus minus3" type="button" value="-">
<input type="number" id="Quantity-collection-template-new" name="quantity" value="1" min="1" class="product-form__input qty" pattern="[0-9]*" data-quantity-input="">
<input class="plus plus3" type="button" value="+">
It's easier to answer this here.
You're using .plus1 and .plus2 but there's no .plus3 bindings on the website. Which is different from what you posted here, that's why is working, so, my advice is:
Just remove the duplicate and use the same logic here, try it again and let us know.
$('.plus').on('click', function(e) { // omitted });
$('.minus').on('click', function(e) { // omitted });
This is what you have right now on the website:
$('.plus1').on('click', function(e) {
var val = parseInt($(this).prev('input').val());
$(this).prev('input').val(val + 1);
});
$('.minus1').on('click', function(e) {
var val = parseInt($(this).next('input').val());
if (val !== 0) {
$(this).next('input').val(val - 1);
}
if (val == 0) {
$(this).next('input').val(1);
}
});
And another section;
$('.plus2').on('click', function(e) {
var val = parseInt($(this).prev('input').val());
$(this).prev('input').val(val + 1);
});
$('.minus2').on('click', function(e) {
var val = parseInt($(this).next('input').val());
if (val !== 0) {
$(this).next('input').val(val - 1);
}
if (val == 0) {
$(this).next('input').val(1);
}
});
A couple of suggestions;
Don't use the same id, create some logic to add at least an index for each id if they represent more or less the same thing. product-1 and product-2 and so on. Same Id is recipe for disaster and a no-no from the start.
Remember to update both id and for properties with unique identifiers.
minus/plus - index works.

I add the max value of three input numbers and it's worked but how to add the increment decrement button without losing the max value?

I need the addition of a three-element is 8, with click + and - button. But, I don't want that it will increase each element up to 8.
// Addtion of select items LINK - https://stackoverflow.com/questions/49644837/set-max-value-of-three-input-numbers-together
var max = 8;
var $inputs = $('input');
function sumInputs($inputs) {
var sum = 0;
$inputs.each(function() {
sum += parseInt($(this).val(), 0);
});
return sum;
}
$inputs.on('input', function(e) {
var $this = $(this);
var sum = sumInputs($inputs.not(function(i, el) {
return el === e.target;
}));
var value = parseInt($this.val(), 10) || 0;
if (sum + value > max) $this.val(max - sum);
});
//Increment Decrement value
function up(max) {
document.getElementById("myNumber").value = parseInt(document.getElementById("myNumber").value) + 1;
if (document.getElementById("myNumber").value >= parseInt(max)) {
document.getElementById("myNumber").value = max;
}
}
function down(min) {
document.getElementById("myNumber").value = parseInt(document.getElementById("myNumber").value) - 1;
if (document.getElementById("myNumber").value <= parseInt(min)) {
document.getElementById("myNumber").value = min;
}
}
function up2(max) {
document.getElementById("myNumber2").value = parseInt(document.getElementById("myNumber2").value) + 1;
if (document.getElementById("myNumber2").value >= parseInt(max)) {
document.getElementById("myNumber2").value = max;
}
}
function down2(min) {
document.getElementById("myNumber2").value = parseInt(document.getElementById("myNumber2").value) - 1;
if (document.getElementById("myNumber2").value <= parseInt(min)) {
document.getElementById("myNumber2").value = min;
}
}
function up3(max) {
document.getElementById("myNumber3").value = parseInt(document.getElementById("myNumber3").value) + 1;
if (document.getElementById("myNumber3").value >= parseInt(max)) {
document.getElementById("myNumber3").value = max;
}
}
function down3(min) {
document.getElementById("myNumber3").value = parseInt(document.getElementById("myNumber3").value) - 1;
if (document.getElementById("myNumber3").value <= parseInt(min)) {
document.getElementById("myNumber3").value = min;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="select-1">
<button type="submit" value="-" onclick=" down('0')" class="sub" id="">-</button>
<input type="number" id="myNumber" value="0" name="qty" max="8" min="0" step="1"/>
<button type="submit" value="+" onclick="up('8')" class="add">+</button>
</div>
<div class="select-2">
<button type="submit" value="-" onclick=" down2('0')" class="sub">-</button>
<input type="number" id="myNumber2" value="0" name="qty2" max="8" min="0" step="1"/>
<button type="submit" value="+" onclick="up2('8')" class="add">+</button>
</div>
<div class="select-3">
<button type="submit" value="-" onclick=" down3('0')" class="sub" id="">-</button>
<input type="number" id="myNumber3" value="0" name="qty3" max="8" min="0" step="1"/>
<button type="submit" value="+" onclick="up3('8')" class="add">+</button>
</div>
Currently, the max value is 8. I would like to get the max value with the + and - button as well.
How can I solve this with javascript or jquery?
Here, there is a link below I follow for increment and decrement.
https://stackoverflow.com/a/49645518/15412266
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<button type="submit" value="+" onclick="minusoperation(1)" class="minus">-</button>
<input type="number" class="numbers" id="number1" min="0" max="8" onchange="inputNumber(this)" data-prevvalue=0 />
<button type="submit" value="+" onclick="plusoperation(1)" class="plus">+</button>
<button type="submit" value="+" onclick="minusoperation(2)" class="minus">-</button>
<input type="number" class="numbers" id="number2" min="0" max="8" onchange="inputNumber(this)" data-prevvalue=0 />
<button type="submit" value="+" onclick="plusoperation(2)" class="plus">+</button>
<button type="submit" value="+" onclick="minusoperation(3)" class="minus">-</button>
<input type="number" class="numbers" id="number3" min="0" max="8" onchange="inputNumber(this)" data-prevvalue=0 />
<button type="submit" value="+" onclick="plusoperation(3)" class="plus">+</button>
</div>
<script type="text/javascript">
function inputNumber(el)
{
var myElements = document.getElementsByClassName('numbers');
var sum = 0;
for (var i=0;i<myElements.length;i++) {
if(myElements[i].value)
sum = sum+parseInt(myElements[i].value);
}
if(sum<=8)
{
el.dataset.prevvalue = el.value;
} else {
el.value = el.dataset.prevvalue;
}
}
function minusoperation(inputNumber)
{
var el = document.getElementById('number'+inputNumber);
if(parseInt(el.value))
{
el.value = parseInt(el.value)-1;
} else {
el.value = 0;
}
el.onchange();
}
function plusoperation(inputNumber)
{
var el = document.getElementById('number'+inputNumber);
if(parseInt(el.value))
{
el.value = parseInt(el.value)+1;
} else {
el.value = 1;
}
el.onchange();
}
</script>
</body>
</html>

JQuery function does not respect clicked component

I have a product page where you can make customizations to the product such as adding or removing "ingredients" and for each customization that can be added or removed I create an input with a + and - button to increase or decrease my choice.
I inform via parameter to the javascript function the component (input) that will receive the increment or decrement, the maximum value that can be increased, the minimum value (decrement) and the increment interval.
However, for each possible customization in the product I must present a component like this:
<div class="qty mt-5">
<span class="minus" name="diminuir[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]" onclick="AumentaDiminui('qty_4', 0, 5, 1)">+</span>
</div>
And this is my java script function that should add or subtract the value and present it in the correct input
<script>
function AumentaDiminui(controle, valorMinimo, valorMaximo, valorIncremento) {
$(document).ready(function () {
$('[name="aumentar[]"]').click(function () {
if ($("[name=" + controle + "]").val() == valorMaximo)
return;
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) + valorIncremento);
});
$('[name="diminuir[]"]').click(function () {
if ($("[name=" + controle + "]").val() <= valorMinimo) {
$("[name=" + controle + "]").val(valorMinimo);
return;
}
$("[name=" + controle + "]").val(parseInt($("[name=" + controle + "]").val()) - valorIncremento);
});
});
}
</script>
It turns out that the value is not incremented by 1 in 1 as I inform via parameter and if I have more than one component on the screen, when clicking on + or - the value of all inputs are changed regardless of the button I click on
A few comments about your code:
If jquery will handle the click events on the <span>, one should not define a onclick event in the span tag.
There is no need to define a function. You can just wait for the ready event and then monitor for clicks on both <span> (using the jquery .click() function).
You can access the values of min and max value defined in the <input> using the jquery .attr() function.
This is a working code:
$(document).ready(function () {
$('.qty .minus, .qty .plus').click(function () {
var input = $(this).parent().find('input[type=number]');
var newVal = +input.val();
var step = +input.attr('step');
if ($(this).hasClass('plus')){
newVal += step;
} else {
newVal -= step;
}
var min = input.attr('min');
var max = input.attr('max');
if (newVal > max) {
newVal = max;
} else if (newVal < min){
newVal = min;
}
input.val(newVal);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Step: 1</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="1" max="5" min="0">
<span class="plus">+</span>
</div>
<p>Step: 2</p>
<div class="qty mt-5">
<span class="minus">-</span>
<input type="number" class="count" value="0" step="2" max="5" min="0">
<span class="plus">+</span>
</div>
There is a much easier way to do this, with just a few data-* attributes. This will work on any number of div elements with these attributes and a plus and minus button.
$('.qty').on('click','.minus', function(){
var $parent = $(this).parent();
var min = $parent.data('min');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val > min)
$input.val(val - inc);
})
$('.qty').on('click','.plus', function(){
var $parent = $(this).parent();
var max = $parent.data('max');
var inc = $parent.data('inc');
var $input = $(this).siblings('.count');
var val = parseInt($input.val(),10);
if(val < max)
$input.val(val + inc);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="qty mt-5" data-min="0" data-max="5" data-inc="1">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
<div class="qty mt-5" data-min="0" data-max="100" data-inc="5">
<span class="minus">-</span>
<input type="number" class="count" name="qty_4" value="0" step="1" max="5" min="0">
<span class="plus" name="aumentar[]">+</span>
</div>
You could also choose to read min, max and step from the input if you prefered with much the same logic.
create an jquery extension
(function($){
$.fn.AumentaDiminui = function(options) {
var settings = $.extend({ control: null, minvalue:1, maxvalue: 5 , action:'+' }, options );
var curval = $(settings .control).val ();
if ('+'==settings.action){
if (curval==settings.maxvalue) return;
curval++;
}
else {
if (curval==settings.minvalue) return;
curval++;
}
$(settings .control).val (curval);
};
}(jQuery));
call so as
$('div.qty.mt-5 span.minus').click(function (){ $.fn.AumentaDiminui({ action:'-', control:'div.qty.mt-5 input.count' }); });
$('div.qty.mt-5 span.plus').click(function (){ $.fn.AumentaDiminui({ action:'+', control:'div.qty.mt-5 input.count' }); });

How to add 1 to a value in an input field with javascript on click?

I have a shopping cart and I want to implement an update quantities per item.. Let me show you that code maybe it will be easier to explain.
HTML:
<div class="custom-quantity-input">
<input type="text" name="quantity" class="" value="<?php echo $items['qty']; ?>">
<i class="fa fa-angle-up"></i>
<i class="fa fa-angle-down"></i>
</div>
I want that when user click on the link add-one to increase the amount on the input field and when they click #decrease to reduce by one the amount on the input field just visually no AJAX or anything.
I don't know much of JavaScript that's why I seek your help.
$(function(){
$(".quantity-input-up").click(function(){
var inpt = $(this).parents(".custom-quantity-input").find("[name=quantity]");
var val = parseInt(inpt.val());
if ( val < 0 ) inpt.val(val=0);
inpt.val(val+1);
});
$(".quantity-input-down").click(function(){
var inpt = $(this).parents(".custom-quantity-input").find("[name=quantity]");
var val = parseInt(inpt.val());
if ( val < 0 ) inpt.val(val=0);
if ( val == 0 ) return;
inpt.val(val-1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-quantity-input">
<input type="number" min="0" name="quantity" class="" value="5">
<i class="fa fa-angle-up">+</i>
<i class="fa fa-angle-down">-</i>
</div>
<div class="custom-quantity-input">
<input type="number" min="0" name="quantity" class="" value="9">
<i class="fa fa-angle-up">+</i>
<i class="fa fa-angle-down">-</i>
</div>
<div class="custom-quantity-input">
<input type="number" min="0" name="quantity" class="" value="200">
<i class="fa fa-angle-up">+</i>
<i class="fa fa-angle-down">-</i>
</div>
I hope this helps:
$( "#more" ).click(function() {
var qtt = parseInt($('#quantity').val(), 10);
$('#quantity').val(qtt+1);
});
$( "#less" ).click(function() {
var qtt = parseInt($('#quantity').val(), 10);
if (qtt > 0) { //does not allow negative values
$('#quantity').val(qtt-1);
}
});
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<input type="text" id="quantity" value="5">
<button id="more" type="button">+</button>
<button id="less" type="button">-</button>
Do not forget to include the jQuery project.
Here's a nicer and more portable solution that accounts for multiple inputs on a page:
jQuery(function($) {
$(".quantity-btn").on("click", function(e) {
e.preventDefault(); // Don't scroll top.
var $inp = $(this).closest("div").find("input"), // Get input
isUp = $(this).is(".quantity-input-up"), // Is up clicked? (Boolean)
currVal = parseInt($inp.val(), 10); // Get curr val
$inp.val(Math.max(0, currVal += isUp ? 1 : -1)); // Assign new val
});
// Other DOM ready code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-quantity-input">
<input type="text" name="quantity" class="" value="0">
▲
▼
</div>
<div class="custom-quantity-input">
<input type="text" name="quantity" class="" value="2">
▲
▼
</div>
the event.preventDefault() is just to make sure your browser does not scroll to top on anchor click.
Quick way:
function initCartCounter(input, upBtn, downBtn) {
upBtn.onclick = () => input.value++;
downBtn.onclick = () => input.value--;
}
//No matter which way you get these elements
initCartCounter(
document.getElementById('val'),
document.links[0],
document.links[1]
);
<input id="val" type="number" value="0"/>
Add
<a href="javascript:;" >Sub</a>
A bit cleaner and scalable:
!function() {
document.querySelectorAll('.cart')
.forEach(cart => {
let input = cart.querySelector('.cart-number');
cart.querySelector('.cart-number-inc')
.addEventListener('click', () => input.innerText = (input.innerText|0)+1);
cart.querySelector('.cart-number-dec')
.addEventListener('click', () => input.innerText = (input.innerText|0)-1);
})
}();
.pointer {cursor: pointer;}
<div class="cart">
<span class="cart-number">0</span>
<span class="cart-number-inc pointer">Add</span>
<span class="cart-number-dec pointer">Dec</span>
</div>
Best way, imo, is to use native input[type=number]:
<input type="number" value="0"/>

change the box of increment decrement

i am trying to make increment decrements box.
check heredemo
i want the box like this
i think need to change in html code
jQuery(function() {
jQuery("div.add-to-cart .qty_pan").append('<div class="inc add">›</div><div class="dec add">‹</div>');
jQuery(".inputQty").on('click', '.add', function() {
var jQueryadd = jQuery(this);
var oldValue = jQueryadd.parent().find("input").val();
var newVal = 0;
if (jQueryadd.text() == "+") {
newVal = parseFloat(oldValue) + 1;
// AJAX save would go here
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
// AJAX save would go here
}
if(oldValue == 1){
newVal = parseFloat(oldValue);
}
}
jQueryadd.parent().find("input").val(newVal);
});
});
<div class="qty_pan">
<input type="number" min="1" max="1000" name="qty" id="qty" value="1" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
</div>
please help me to edit this box with same functionality
Following is thing which you like to do.
$(function(){
$("#plus").click(function(){
$("#qty").val( Number($("#qty").val()) + 1 );
});
$("#minus").click(function(){
$("#qty").val( Number($("#qty").val()) - 1 );
});
});
.btnplus{
display:inline-block;
}
.qty_pan{
display:inline-block;
}
.btnminus{
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="plus" class="btnplus">+</button>
<div class="qty_pan">
<input type="text" min="1" max="1000" name="qty" id="qty" value="1" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
</div>
<button id="minus" class="btnminus">-</button>
And Changes/Updating in your code is following:
jQuery(function() {
jQuery("div.add-to-cart .qty_pan").append('<div class="inc add">›</div><div class="dec add">‹</div>');
jQuery("#plus, #minus").click(function(){
var jQueryadd = jQuery(this);
var oldValue = jQueryadd.parent().find("input").val();
var newVal = 0;
if (jQueryadd.text() == "+") {
newVal = parseFloat(oldValue) + 1;
// AJAX save would go here
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
// AJAX save would go here
}
if(oldValue == 1){
newVal = parseFloat(oldValue);
}
}
jQueryadd.parent().find("input").val(newVal);
});
});
.btnplus{
display:inline-block;
}
.qty_pan{
display:inline-block;
}
.btnminus{
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="plus" class="btnplus">+</button>
<div class="qty_pan">
<input type="number" min="1" max="1000" name="qty" id="qty" value="1" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
</div>
<button id="minus" class="btnminus">-</button>
Hope it helps.
Try this:
$('#inc, #dec').on('click', function(){
var val = +$('#qty').val();
this.id === "inc" ? $('#qty').val(val+1) : $('#qty').val(val-1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="qty_pan">
<span id='dec'> - </span><input type="number" min="1" max="1000" name="qty" id="qty" value="1" title="" class="input-text qty" /><span id='inc'> + </span>
</div>

Categories

Resources