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.
Related
let plus_btns = document.querySelectorAll('#plus-button');
let minus_btns = document.querySelectorAll('#minus-button');
let qty_inputs = document.querySelectorAll('#quantity');
plus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
qty_inputs.forEach(qty=>{
qty.value++
})
})
})
minus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
qty_inputs.forEach(qty=>{
if(qty.value > 1){
qty.value--
}
else{
qty.value=0;
}
})
})
})
<div class="cart-totals">
<input type="button" value="-" id="minus-button" for="quantity">
<input type="number" id="quantity" value="1" min="0">
<input type="button" value="+" id="plus-button" for="quantity">
<input type="button" value="-" id="minus-button" for="quantity">
<input type="number" id="quantity" value="1" min="0">
<input type="button" value="+" id="plus-button" for="quantity">
</div>
How I can change value of specific quantity input ???
In my case click event triggers all inputs and change the value of each input.
Please guide me thanks.
This should do the trick.
let plus_btns = document.querySelectorAll('#plus-button');
let minus_btns = document.querySelectorAll('#minus-button');
let qty_inputs = document.querySelectorAll('#quantity');
plus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
btn.previousElementSibling.value++;
})
})
minus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
btn.nextElementSibling.value = (btn.nextElementSibling.value == 0) ? 0 : btn.nextElementSibling.value - 1;
})
})
Use event delegation for a single generic document wide handler. Afaik for is not a valid attribute for input type 'button', so use a data-attribute. Furthermore: element id must be unique. Fixed all that in this demo snippet:
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.type === "button") {
return handleBtn(evt.target);
}
}
function handleBtn(btn) {
const elem = document.querySelector(`#${btn.dataset.for}`);
const nwValue = +elem.value + (btn.value === "-" ? -1 : 1);
elem.value = nwValue >= +elem.min ? nwValue : elem.min;
}
<div class="cart-totals">
<input type="button" value="-" data-for="quantity1">
<input type="number" id="quantity1" value="1" min="0">
<input type="button" value="+" data-for="quantity1">
<input type="button" value="-" data-for="quantity2">
<input type="number" id="quantity2" value="1" min="1">
<input type="button" value="+" data-for="quantity2">
</div>
Using a single event handler:
var cart = document.querySelector('.cart-totals');
cart.addEventListener('click', function(ev) {
var tgt = ev.target;
if (tgt.matches('input[type="button"]')) {
var input = document.getElementById(tgt.dataset.for);
var currentValue = +input.value;
var minValue = +input.min;
if (tgt.value === '+') {
input.value = currentValue + 1;
}
else if (currentValue > minValue) {
input.value = currentValue - 1;
}
}
});
<div class="cart-totals">
<input type="button" value="-" data-for="quantity1">
<input type="number" id="quantity1" value="1" min="0">
<input type="button" value="+" data-for="quantity1">
<input type="button" value="-" data-for="quantity2">
<input type="number" id="quantity2" value="5" min="2">
<input type="button" value="+" data-for="quantity2">
</div>
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' }); });
WooCommerce Add To Cart Button text change using jQuery if Quantity increase.
jQuery(document).on("change",'.minus', function() {
var productquantity = jQuery('.qty').attr('value');
if (productquantity == 15) {
jQuery('.single-product').each(function() {
jQuery(".single_add_to_cart_button").text("REQUEST A QUOTE");
});
}
})
While selecting buttons value never changes :S
HTML FOR BUTTON AND SELECTOR
<div class="quantity buttons_added">
<input type="button" value="-" class="minus button is-form"><input type="number" step="1" min="1" max="9999" name="quantity" value="1" title="Qty" class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric"><input type="button" value="+" class="plus button is-form"></div>
<button type="submit" name="add-to-cart" value="1520" class="single_add_to_cart_button button alt" style="display: block !important">Add to Cart</button>
jsFiddle
$(document).ready(function ()
{
$('body').on("click",'.minus',function ()
{
var qtyval = $('.qty').val();
if(qtyval >= 0)
{
var newQTY = parseInt(qtyval) - parseInt(1);
if(newQTY >= 15)
{
$('.single_add_to_cart_button').text("Request a Quote");
}
if(newQTY < 15)
{
$('.single_add_to_cart_button').text("Add to Cart");
}
$('.qty').val(newQTY);
}
});
$('body').on("click",'.plus',function ()
{
var qtyval = $('.qty').val();
var newQTY = parseInt(qtyval) + parseInt(1);
if(newQTY >= 15)
{
$('.single_add_to_cart_button').text("Request a Quote");
}
$('.qty').val(newQTY);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="quantity buttons_added">
<input type="button" value="-" class="minus button is-form"><input type="number" step="1" min="1" max="9999" name="quantity" value="1" title="Qty"
class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric"><input type="button" value="+" class="plus button is-form"></div>
<button type="submit" name="add-to-cart" value="1520" class="single_add_to_cart_button button alt" style="display: block !important">Add to Cart</button>
jQuery(document).on("click",'.plus, .minus', function() {
var productquantity = jQuery('.qty').attr('value');
if (productquantity == 15) {
jQuery('.single-product').each(function() {
jQuery(".single_add_to_cart_button").text("REQUEST A QUOTE");
});
} else if(productquantity != 15) {
jQuery('.single-product').each(function() {
jQuery(".single_add_to_cart_button").text("ADD TO CART NOW");
});
}
})
Only problem was on change to onclick.
I have a form with this inputs and buttons :
<input type="number" id="inputs" name="inputs" min="3" max="48" pattern=".{1,2}" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id ="button2" value="next">
And I'm using this javascript code to append number of the "inputs" that the user have insert in this button :
$(function()
{
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=1;i<=c;i++)
{
$("#mydiv").append('<input type="text" id="name'+i+'" name="name'+i+'" placeholder="name'+i+'">');
$("#mydiv").append('<input type="number" id="rating'+i+'" name="rating'+i+'" min="1" max="10" placeholder="rating'+i+'"><br/>');
}
});
$("#button2").click(function()
{
if(c===0)
alert('must click on "continue" button');
});
});
});
I'm trying to require the user to enter a value in "inputs" (input type) and click on the "continue" (button1) button. With that way it's not working (must enter a value in the "inputs" but can click on "button2" without clicking on "button1"). How do I require the user to click also on the "button1" (continue) ?
Thanks.
$(function() {
var c = 0;
$("#button1").click(function() {
if( !$('#inputs')[0].checkValidity() ) {
alert( $('#inputs')[0].title );
return false;
}
c = +$("#inputs").val();
$("#mydiv").html("");
for (i = 1; i <= c; i++) {
$("#mydiv").append('<input type="text" id="name' + i + '" name="name' + i + '" placeholder="name' + i + '">');
$("#mydiv").append('<input type="number" id="rating' + i + '" name="rating' + i + '" min="1" max="10" placeholder="rating' + i + '"><br/>');
}
$('#button2').prop('disabled',false);
});
$("#button2").click(function() {
if (c === 0) {
alert('must click on "continue" button');
} else {
alert('Now let us move ahead');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="inputs" name="inputs" min="3" max="48" pattern=".{1,2}" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id="button2" value="next" disabled>
$(function() {
var c = 0;
$("#button1").click(function() {
if ($("#inputs").val().length > 0 && $("#inputs").val().length < 3 && $("#inputs").val() != 0) {
c = $("#inputs").val();
$("#mydiv").html("");
for (i = 1; i <= c; i++) {
$("#mydiv").append('<input type="text" id="name' + i + '" name="name' + i + '" placeholder="name' + i + '">');
$("#mydiv").append('<input type="number" id="rating' + i + '" name="rating' + i + '" min="1" max="10" placeholder="rating' + i + '"><br/>');
}
$("#button2").prop('disabled', false);
} else {
$("#button2").prop('disabled', true);
alert("Value is empty / to low / to high. Insert a value between 1 and 99");
}
});
$("#button2").click(function() {
if(c > 0 && $("#inputs").val() > 0){
alert('piu piu');
}
else{
alert('sorry, check your inputs');
$("#button2").prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="inputs" name="inputs" min="3" max="48" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id="button2" value="next" disabled>
You can disable button2 and make it enable on click of button1, see below code
<input type="number" id="inputs" name="inputs" min="3" max="48" pattern=".{1,2}" required title="please enter a value between 3 to 48">
<input type="button" id="button1" value="continue">
<div id="mydiv"></div>
<input type="submit" id ="button2" value="next" disabled>
jQuery
$(function()
{
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val().trim();
$("#mydiv").html("");
for(i=1;i<=c;i++)
{
$("#mydiv").append('<input type="text" id="name'+i+'" name="name'+i+'" placeholder="name'+i+'">');
$("#mydiv").append('<input type="number" id="rating'+i+'" name="rating'+i+'" min="1" max="10" placeholder="rating'+i+'"><br/>');
}
//enable your button 2 if input has value
if(c!='')
$("#button2").removeProp('disabled');
});
$("#button2").click(function()
{
//submit your form here
});
});
Change this line:
c = $("#inputs").val();
to
if($("#inputs").val() != "")
c = $("#inputs").val();
I have 3 inputs and I'm trying to get the sum of the numbers each time a user updates one of them.
HTML
<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">
JS
var sum = 0;
$('.my-input').each(function(index, elem){
var value = $(this).val();
sum += parseFloat($(elem).val());
console.log(sum);
$(this).on('keyup click', function (){
sum += parseFloat($(elem).val());
});
});
But I keep getting crazy results..
EDIT:
I tried this:
function getSum(){
var sum = 0;
$('.my-input').each(function(index, elem){
var value = $(this).val();
sum += parseFloat($(elem).val());
});
return sum;
}
$('.my-input').each(function(){
$(this).on('keyup click', function(){
console.log( this.value );
var curSum = getSum();
console.log('current sum: ' + curSum);
});
});
Consider this example:
<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input type="text" id="total" value="" />
<script type="text/javascript">
// just get keyup event
$('.my-input').on('keyup', function(){
var total = 0;
// on every keyup, loop all the elements and add all the results
$('.my-input').each(function(index, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
});
$('#total').val(total);
});
</script>