简体   繁体   中英

JQuery DOM manipulation: sum of 2 numbers generate NaN even if using parseInt()

I have multiple input type="number" on my page. They are dinamically generated each time a user clicks on a "add-form-row" button. I want to give as value to a h2 element in my DOM based on the sum of each of these input each time a new input is added. When I try to sum the inputs, though, a NaN is returned. How can I fix this?

 $(document).on('click', '.add-form-row', function(e){ e.preventDefault(); //cloneMore('.form-row:last', 'elements'); // here starts the sum logic var tot = 0; currentTotal = $('.form-row').find('input[type=number]').each(function() { numberPrice = parseInt($(this).val()) tot += numberPrice }); $('.totalPrice').text(`<span>${tot}</span>`) return false; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-row"> <input type="number" value="1"> <input type="number" value="2"> <button class="add-form-row">add</button> <div class="totalPrice"></div> </div>

If any of the input value is ="" , ie nothing, the total will be NaN , because parseInt("") = NaN , so maybe adding a condition like this can solve your problem:

$(document).on('click', '.add-form-row', function(e){
        e.preventDefault();
        //cloneMore('.form-row:last', 'elements');
        // here starts the sum logic
        var tot = 0;
        currentTotal = $('.form-row').find('input[type=number]').each(function() {
            if($(this).val() != ""){
                numberPrice = parseInt($(this).val());
                tot += numberPrice;
            }
        });
        $('.totalPrice').text(`<span>${tot}</span>`);
        return false;
    });

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