简体   繁体   中英

Add/minus number inside a input field on Click

This is my Fiddle: https://jsfiddle.net/55L52yww/93/

Example 1 (integer) Works fine

Example 2 (float):

  • Problems with adding on second time, and on 8th ~ time

  • if you press on minus it jumps to 0.15, even if the value is 0.75 it will jump to 0.15 (this one I fixed, just missed a parseFloat https://jsfiddle.net/55L52yww/94/ )

How can I fix example 2? Thanks for any help

// The button to increment the product value
$(document).on('click', '.product_quantity_up', function(e){
    e.preventDefault();
    var arrayData = $(this).data('field-qty');
    var arr = arrayData.split(';');
    for (i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }
    fieldName = arr[0];
    var currentVal = parseFloat($('input[name='+fieldName+']').val());
    var minimalVal = parseFloat($('input[name='+fieldName+']').attr("data-minimal_quantity"));

    if (!isNaN(currentVal) && currentVal < minimalVal) {
        $('input[name='+fieldName+']').val(minimalVal);
        $(this).parent().parent().find(".ajax_add_to_cart_button").attr("data-minimal_quantity",minimalVal);
    }
    else {
        $('input[name='+fieldName+']').val(currentVal + parseFloat(arr[1])).trigger('keyup');
        $(this).parent().parent().find(".ajax_add_to_cart_button").attr("data-minimal_quantity",currentVal + parseFloat(arr[1]));
    }

    $('#'+fieldName).change();



});
 // The button to decrement the product value
$(document).on('click', '.product_quantity_down', function(e){
    e.preventDefault();
    var arrayData = $(this).data('field-qty');
    var arr = arrayData.split(';');
    for (i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }
    fieldName = arr[0];
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    var minimalVal = parseFloat($('input[name='+fieldName+']').attr("data-minimal_quantity"));

    if (!isNaN(currentVal) && currentVal > minimalVal){
        $('input[name='+fieldName+']').val(currentVal - parseFloat(arr[1])).trigger('keyup');
        $(this).parent().parent().find(".ajax_add_to_cart_button").attr("data-minimal_quantity",currentVal - parseFloat(arr[1]));
    }
    else {
        $('input[name='+fieldName+']').val(minimalVal);
        $(this).parent().parent().find(".ajax_add_to_cart_button").attr("data-minimal_quantity",minimalVal);
    }

    $('#'+fieldName).change();

});

In the second event handler, you still use parseInt to get currentValue :

var currentVal = parseInt($('input[name='+fieldName+']').val());

So that needs to be:

var currentVal = parseFloat($('input[name='+fieldName+']').val());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM