+ Start a Discussion
Puja ChoudharyPuja Choudhary 

jquery incrementor

I am using a jquey incrementor and decrementor button in add to cart vf page for increasing and decreasing quantity.Initially i was using a number field 

and the code below is working fine to increment the cart value
 $(document).on("input", "." + classProductQuantity, function () {
      var price = $(this).closest("tr").data("price");
      var id = $(this).closest("tr").data("id");
      var quantity = $(this).val();
      alert(quantity);
      alert(price);
      $(this).parent("td").next("." + classProductTotal).text("Rs " + price * quantity);
      ProductManager.updatePoduct(id, quantity);

      $cartBadge.text(ProductManager.getTotalQuantity());
      showGrandTotal();
      showDiscountPrice();
    });

As number field is not working in tablet, I am using jquery to replace the number field.

var drawTable = function(){
      var $cartTable = $("#" + idCartTable);
      $cartTable.empty();

      var products = ProductManager.getAllProducts();
      $.each(products, function(){
        var total = this.quantity * this.price;
        $cartTable.append(
          '<tr title="' + this.summary + '" data-id="' + this.id + '" data-price="' + this.price + '">' +
          '<td class="text-center" style="width: 30px;"><img width="30px" height="30px" src="' + this.image + '"/></td>' +
          '<td>' + this.name + '</td>' +
          '<td title="Unit Price">Rs ' + this.price + '</td>' +
          '<td title="Quantity">'+      
          '<div class="center">'+
          '<div class="input-group">'+
          '<span class="input-group-btn">'+
              '<button type="button" class="btn btn-default btn-number" data-type="minus" data-field="' + this.id + '">'+
                  '<span class="glyphicon glyphicon-minus"></span>'+
              '</button>'+
          '</span>'+
          '<input type="text" name="' + this.id + '"  class="' + classProductQuantity + ' form-control input-number" value="' + this.quantity + '" min="1" max="20">'+
          '<span class="input-group-btn">'+
              '<button type="button" class="btn btn-default btn-number" data-type="plus" data-field="' + this.id + '">'+
                  '<span class="glyphicon glyphicon-plus"></span>'+
              '</button>'+
          '</span>'+
          '</div>'+
          '</div>'+
          '</td>' + 
            '<td title="Total" class="' + classProductTotal + '"> Rs ' + total + '</td>' +
          
          '<td title="Remove from Cart" class="text-center" style="width: 30px;"><a href="javascript:void(0);" class="btn btn-xs btn-danger ' + classProductRemove + '">X</a></td>' +
          '</tr>'
        );
       
    $(document).ready(function(){     
        $('.btn-number').click(function(e){
        e.preventDefault();
        var fieldName = $(this).attr('data-field');
        var type = $(this).attr('data-type');
        var input = $("input[name='"+fieldName+"']");
        var currentVal = parseInt(input.val());
        var price = $(this).closest("tr").data("price");
        var id = $(this).closest("tr").data("id");
        alert(price);
        alert(id);
        alert(currentVal)
        if (!isNaN(currentVal)) 
        {
            if(type == 'minus') 
            {
            
                if(currentVal > input.attr('min')) 
                {
                  
                    input.val(currentVal - 1).change();
                } 
                if(parseInt(input.val()) == input.attr('min')) {
                    $(this).attr('disabled', true);
                }
              
               $(this).parent("td").next("." + classProductTotal).text("Rs " + price * quantity);
               ProductManager.updatePoduct(id, quantity);
               alert("ok");
      $cartBadge.text(ProductManager.getTotalQuantity());
      showGrandTotal();

        } else if(type == 'plus') 
        {

            if(currentVal < input.attr('max')) {
                input.val(currentVal + 1).change();
            }
            if(parseInt(input.val()) == input.attr('max')) {
                $(this).attr('disabled', true);
            }

        }
        
    } 
    else 
    {
        input.val(0);
    }
     
});




$('.input-number').focusin(function(){
  $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {
    
    minValue =  parseInt($(this).attr('min'));
    maxValue =  parseInt($(this).attr('max'));
    valueCurrent = parseInt($(this).val());
    name = $(this).attr('name');
    if(valueCurrent >= minValue) {
        $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled')
    } else {
        alert('Sorry, the minimum value was reached');
        $(this).val($(this).data('oldValue'));
    }
    if(valueCurrent <= maxValue) {
        $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled')
    } else {
        alert('Sorry, the maximum value was reached');
        $(this).val($(this).data('oldValue'));
    }
    
    
});
$(".input-number").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
   });
});

So, the problem is the value is increasing and decreasing properly.But when i am closing the cart ....the value is getting reset to the initial value...ie it is not holding the value.
User-added image
and also the quantity and price is not getting multiplied.
Alain CabonAlain Cabon
Hi,

I am not sure (not tested) but it seems that it lacks the code in bold for "plus" (or you have removed it in the code above yet);

    if (!isNaN(currentVal)) 
    {
      if(type == 'minus') 
      {            
                if(currentVal > input.attr('min')) {                
                    input.val(currentVal - 1).change();
                } 
                if(parseInt(input.val()) == input.attr('min')) {
                    $(this).attr('disabled', true);
                }             
        } else
        if(type == 'plus') 

        {
            if(currentVal < input.attr('max')) {
                input.val(currentVal + 1).change();
            }
            if(parseInt(input.val()) == input.attr('max')) {
                $(this).attr('disabled', true);
            }
     }
    else 
    {
        input.val(0).change();
    }
    if(type == 'minus' || type == 'plus')
    {
         
  var quantity =  parseInt(input.val());
            $(this).parent("td").next("." + classProductTotal).text("Rs " + price * quantity);
            ProductManager.updatePoduct(id, quantity);
            alert("ok");
             $cartBadge.text(ProductManager.getTotalQuantity());
            showGrandTotal();
      
     }

    Regards
Puja ChoudharyPuja Choudhary
What is the use of making some portion of the code bold?
and how can i do this?
Alain CabonAlain Cabon
Hi,

It is just to show the difference between the codes and perform copy/paste operation (using bold type and/or underlining to emphasize important information has no effect in Salesforce during the program execution).

The alternative if(type == 'plus') doesn't perform the code in bold like: $(this).parent("td").next("." + classProductTotal).text("Rs " + price * quantity);

Given that we don't see all the code (methods ProductManager.updatePoduct(); ProductManager.getTotalQuantity() or  showGrandTotal(); ), it lacks some information for facilitating support.

Regards
Puja ChoudharyPuja Choudhary
yes....This is a long code so I didn't put the whole thing.
Can I send you the whole code?
Puja ChoudharyPuja Choudhary
Hi Alain Cabon,
Thank you for your help...The code you provided is working well separately but I want to implement the function in my code .

I took some idea from your code and implemented in mine. Now the plus and minus icon is working fine but still the changes are showing in the popup after i close the popup and reopen it again.

The popup window code is :

var products = ProductManager.getAllProducts();
 $.each(products, function(){
        var total = this.quantity * this.price;
        $cartTable.append(
          '<tr title="' + this.summary + '" data-id="' + this.id + '" data-price="' + this.price + '">' +
          '<td class="text-center" style="width: 30px;"><img width="30px" height="30px" src="' + this.image + '"/></td>' +
          '<td>' + this.name + '</td>' +
          '<td title="Unit Price">Rs ' + this.price + '</td>' +
          
          '<td title="Quantity">'+
          '<div class="center">'+
          '<div class="input-group">'+
          '<span class="input-group-btn">'+
          '<button type="button" id="btnm" class="' + classProductQuantity + ' btn btn-default btn-number" value="' + this.quantity + '" data-type="minus" data-field="' + this.id + '">'+
                  '<span class="glyphicon glyphicon-minus"></span>'+
             '</button>'+
          '</span>'+
          '<input type="text" id="txt1" name="' + this.id + '"  class="' + classProductQuantity + ' form-control input-number" value="' + this.quantity + '" min="1" max="20">'+
          '<span class="input-group-btn">'+
          '<button type="button" id="btnp" class="' + classProductQuantity + ' btn btn-default btn-number" value="' + this.quantity + '" data-type="plus" data-field="' + this.id + '">'+
                  '<span class="glyphicon glyphicon-plus"></span>'+
            '</button>'+
          '</span>'+
          '</div>'+
          '</div>'+
          '</td>' +
          
        '<td title="Total" class="' + classProductTotal + '"> Rs ' + total + '</td>' +


         '<td title="Remove from Cart" class="text-center" style="width: 30px;"><a href="javascript:void(0);" class="btn btn-xs btn-danger ' + classProductRemove + '">X</a></td>' +
          '</tr>'
        );
   });   

and the modified java script

$(document).on("click", "." + classProductQuantity, function () {
      var price = $(this).closest("tr").data("price");
      var id = $(this).closest("tr").data("id");
      var quantity = $(this).val();
      var type = $(this).attr('data-type');
      
         
      if(type == 'minus') 
                {
                    if(quantity > 1) 
                    {
                        --quantity;
                        this.value= quantity;
                        
                     }
                     
                     if(quantity == 1) {
                    $(this).attr('disabled', true);
                    }
                 }
                
                else if(type == 'plus') 
            {

                if(quantity < 20) {
                    ++quantity;
                    this.value= quantity;
                    
                }
                
                if(quantity == 20) {
                $(this).attr('disabled', true);
                }
                

            }
       
      $(this).parent("td").next("." + classProductTotal).text("Rs " + price * quantity);
      ProductManager.updatePoduct(id,quantity);


      $cartBadge.text(ProductManager.getTotalQuantity());
      showGrandTotal();
      showDiscountPrice();
    }); 


I want that when i increase quantity the total price(ie. price*quantity should increase automatically). but for now it is not working instantly. I think
these two lines are not working.
$(this).parent("td").next("." + classProductTotal).text("Rs " + price * quantity);
ProductManager.updatePoduct(id,quantity);

**Can you give me your email address so that i can email you the whole code because i have given just one part here,
Alain CabonAlain Cabon
Hi Puja Choudhary,

You have a very difficult work to do (popup javascript + jquery + salesforce).

My sample code is simple and doesn't solve all your problems. 

For the complete integration in Salesforce, there are other problems to solve.

Do not hesitate to use other forums with your problem if you have not already done so. An other developper could have a complete solution very close to your need: 

https://success.salesforce.com/

https://salesforce.stackexchange.com/


We often need to use the following method ( noConflict ) and we replace $ with j$ everywhere.
view sourceprint?
 
j$ = jQuery.noConflict();
j$('.accountDiv').click(function () {
    j$(this).toggle();
});​


User-added image
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script>
$(function () {

$(document).on('click', '.reset', function () {
	$('#passengers').val(0);
	$("[id$='_value']").val(0);
	$("[id$='_subtotal']").text(0);
	$("[id$='_price']").val(0);
	$("#grandtotal").text(0);
	$("#item_val").val(10);
});

$(document).on('click', '.addrow', function () {
	var newrow = '<div class="row">' +
		'<label class="control-label col-md-3"><strong>' + $('#item_text').val() + '</strong><br> <i>(new)</i></label>' +
		'<div class="input-group number-spinner col-md-6">' +
		'<label id="infant_price" class="control-label col-md-3">' + $('#item_val').val() + '</label>' +
		'<span class="input-group-btn">' +
		'<a class="btn btn-danger" data-dir="dwn"><span class="glyphicon glyphicon-minus"></span></a>' +
		'</span>' +
		'<input type="text" disabled name="infant" id="infant_value" class="form-control text-center col-md-2" value="0" max="10" min="0" />' +
		'<span class="input-group-btn">' +
		'<a class="btn btn-info" data-dir="up"><span class="glyphicon glyphicon-plus"></span></a>' +
		'</span>' +
		'<label id="infant_subtotal" class="control-label col-md-3">0</label>' +
		'<span  class="input-group-btn">' +
		'<a class="btn btn-danger" data-dir="remove"><span class="glyphicon  glyphicon-remove"></span></a>' +
		'</span>' +
		'</div>' +
		'</div>';
	$('.content').append(newrow);
});

// spinner(+-btn to change value) & total to parent input
$(document).on('click', '.number-spinner a', function () {
	var btn = $(this);
	var input = btn.closest('.number-spinner').find("[id$='_value']");
	var oldValue = parseInt(input.val().trim());

	if (btn.attr('data-dir') == 'up') {
		if (parseInt(oldValue) < parseInt(input.attr('max'))) {
			oldValue++;
		}
	} else if (btn.attr('data-dir') == 'dwn') {
		if (parseInt(oldValue) > parseInt(input.attr('min'))) {
			oldValue--;
		}
	} else if (btn.attr('data-dir') == 'remove') {
		btn.parents('.row').remove();
	}
	price = parseInt(btn.closest('.number-spinner').find("[id$='_price']").text());
	subtotal = price * oldValue;
	btn.closest('.number-spinner').find("[id$='_subtotal']").text(subtotal);
	input.val(oldValue);
	var grand_total = 0
		$("[id$='_subtotal']").each(function (index, element) {
			grand_total += parseInt($(this).text());
		});
	$("#grandtotal").text(grand_total);

	var total = 0
		$("[id$='_value']").each(function (index, element) {
			total += parseInt($(this).val());
		});
	$('#passengers').val(total);

});
});
</script>
</head>
<body>
<div class="container">
    <h3>Passenger Number Input ( Spinner Input )</h3>
	<div class="col-md-6">   
            <div class="content">
			 <div class="row">
			   <label class="control-label col-md-3">Passenger Total:</label>
			   <div class="inputdefault col-md-6">       
                  <input type="number" name="passengers" id="passengers" class="form-control text-center" value="1" disabled>
		     </div>  
		     <label id="grandtotal" class="control-label">0</label>       
			</div>
            <div class="row">
                     <label class="control-label col-md-3"><strong>Adult</strong><br> <i> (above 17)</i></label>			     
                     <div class="input-group number-spinner col-md-6">
					   <label id="adult_price" class="control-label col-md-3">100</label>
                       <span  class="input-group-btn">
                            <a class="btn btn-danger" data-dir="dwn"><span class="glyphicon glyphicon-minus"></span></a>
                        </span>
                        <input type="text" disabled name="adult" id="adult_value" class="form-control text-center col-md-2" value="0" max="10" min="0" />
                        <span  class="input-group-btn">
                            <a class="btn btn-info" data-dir="up"><span class="glyphicon glyphicon-plus"></span></a>
                        </span>
						<label id="adult_subtotal" class="control-label col-md-3">0</label>
						 <span  class="input-group-btn">
						 <a class="btn btn-danger" data-dir="remove"><span class="glyphicon  glyphicon-remove"></span></a>
						</span>
                    </div>					
                </div>
               <div class="row">
                   <label class="control-label col-md-3"><strong>Child</strong><br> <i> (3 - 17)</i></label>			  
                   <div class="input-group number-spinner col-md-6">
				        <label id="child_price" class="control-label col-md-3">50</label>
                        <span class="input-group-btn">
                            <a class="btn btn-danger" data-dir="dwn"><span class="glyphicon glyphicon-minus"></span></a>
                        </span>
                        <input type="text" disabled name="child" id="child_value" class="form-control text-center col-md-2" value="0" max="10" min="0" />
                        <span class="input-group-btn">
                            <a class="btn btn-info" data-dir="up"><span class="glyphicon glyphicon-plus"></span></a>
                        </span>
						<label id="child_subtotal" class="control-label col-md-3">0</label>
						 <span  class="input-group-btn">
						   <a class="btn btn-danger" data-dir="remove"><span class="glyphicon  glyphicon-remove"></span></a>
						</span>
                    </div>				
                </div>
                <div class="row">
                   <label class="control-label col-md-3"><strong>Infant</strong><br> <i> (below 2)</i></label>			 
                   <div class="input-group number-spinner col-md-6">
					    <label id="infant_price" class="control-label col-md-3">25</label>
                        <span class="input-group-btn">
                            <a class="btn btn-danger" data-dir="dwn"><span class="glyphicon glyphicon-minus"></span></a>
                        </span>
                        <input type="text" disabled name="infant" id="infant_value" class="form-control text-center col-md-2" value="0" max="10" min="0" />
                        <span class="input-group-btn">
                            <a class="btn btn-info" data-dir="up"><span class="glyphicon glyphicon-plus"></span></a>
                        </span>
					   <label id="infant_subtotal" class="control-label col-md-3">0</label>
					  <span  class="input-group-btn">
						 <a class="btn btn-danger" data-dir="remove"><span class="glyphicon  glyphicon-remove"></span></a>
					 </span> 
                    </div>	               
                </div>	   
		  </div>
                <a class="btn btn-default btn-block reset">Reset</a></br>	
				<input type="text"  name="newitem" id="item_text" class="form-control text-center" value="item new"/></br>
				<input type="text"  name="newvalue" id="item_val" class="form-control text-center" value="10"/></br>
                <a class="btn btn-default btn-block addrow">Add row</a>							
        </div>       
	</div>
</div>
</body>
</html>

Even if you send me all your code, I could not reproduce all your environment easily.

You will become an excellent javascript developper once you successfully complete this difficult development (better than me).

Regards
Alain
Alain CabonAlain Cabon
Another important advice: always use JSLINT and JSFORMAT (with Notepad++ for example, it is a free tool)

The following javascript code is "perfect" for JSLINT.  You won't notice the differences with the previous code above but there are many and all is VERY important in Javascript. 
<script>
"use strict";

/*jslint browser: true*/
/*global $, jQuery, alert*/

$(function () {

    $(document).on('click', '.reset', function () {
        $('#passengers').val(0);
        $("[id$='_value']").val(0);
        $("[id$='_subtotal']").text(0);
        $("[id$='_price']").val(0);
        $("#grandtotal").text(0);
        $("#item_val").val(10);
    });

    $(document).on('click', '.addrow', function () {
        var newrow = '<div class="row">' +
            '<label class="control-label col-md-3"><strong>' + $('#item_text').val() + '<\/strong><br> <i>(new)<\/i><\/label>' +
            '<div class="input-group number-spinner col-md-6">' +
            '<label id="infant_price" class="control-label col-md-3">' + $('#item_val').val() + '<\/label>' +
            '<span class="input-group-btn">' +
            '<a class="btn btn-danger" data-dir="dwn"><span class="glyphicon glyphicon-minus"><\/span><\/a>' +
            '<\/span>' +
            '<input type="text" disabled name="infant" id="infant_value" class="form-control text-center col-md-2" value="0" max="10" min="0" \/>' +
            '<span class="input-group-btn">' +
            '<a class="btn btn-info" data-dir="up"><span class="glyphicon glyphicon-plus"><\/span><\/a>' +
            '<\/span>' +
            '<label id="infant_subtotal" class="control-label col-md-3">0<\/label>' +
            '<span  class="input-group-btn">' +
            '<a class="btn btn-danger" data-dir="remove"><span class="glyphicon  glyphicon-remove"><\/span><\/a>' +
            '<\/span>' +
            '<\/div>' +
            '<\/div>';
        $('.content').append(newrow);
    });

    // spinner(+-btn to change value) & total to parent input
    $(document).on('click', '.number-spinner a', function () {
        var btn = $(this),
            input = btn.closest('.number-spinner').find("[id$='_value']"),
            oldValue = parseInt(input.val().trim(), 10),
			price = 0,
			subtotal = 0,
		    grand_total = 0,
			total = 0;

        if (btn.attr('data-dir') === 'up') {
            if (parseInt(oldValue, 10) < parseInt(input.attr('max'), 10)) {
                oldValue += 1;
            }
        } else if (btn.attr('data-dir') === 'dwn') {
            if (parseInt(oldValue, 10) > parseInt(input.attr('min'), 10)) {
                oldValue -= 1;
            }
        } else if (btn.attr('data-dir') === 'remove') {
            btn.parents('.row').remove();
        }
        price = parseInt(btn.closest('.number-spinner').find("[id$='_price']").text(), 10);
        subtotal = price * oldValue;
        btn.closest('.number-spinner').find("[id$='_subtotal']").text(subtotal);
        input.val(oldValue);
        $("[id$='_subtotal']").each(function (index, element) {
            grand_total += parseInt($(this).text(), 10);
        });
        $("#grandtotal").text(grand_total);

        $("[id$='_value']").each(function (index, element) {
            total += parseInt($(this).val(), 10);
        });
        $('#passengers').val(total);
    });
});
</script>

Notepad++ with JSTOOL for formatting the code and JSLINT for the control of quality:

User-added image

The remaining errors are in the html code (outside the script).

Best regards
Alain