Search code examples
javascriptincrement

How increment with 0.5 for first increment and then with 1 using js


i want to add 0.5 for the first increment and then with 1 and the value is starts with 0.5 ,That is i want a logic like below

if(quantity==0.5)
$('#quantity_'+Id).val(quantity+=0.5);
else
$('#quantity_'+Id).val(++quantity);

here my original code

<input type="text" id="quantity_<?php echo $j ;?>"  data-id="<?php echo $j;?>" value="<?= 0.5 ?>" disabled> 

here my javascript

  $('.container').on('click','.button-plus',function () {
            var Id=$(this).data('id');
            var quantity=$('#quantity_'+Id).val();
            $('#quantity_'+Id).val(++quantity);
            calcAmount(Id);
    });

Solution

  • $(`#quantity_${Id}`).val(parseFloat(quantity) <= 0.5 ? (parseFloat(quantity) + 0.5) : (parseInt(quantity) + 1) );
    

    When you get value from any html element, that's string so you can not compare with float/int as you trying to do in above example. try this one hope it helps you.