Correcting Error Nan

Asked

Viewed 39 times

2

Where is wrong to generate this error? I believe it is in var preco = $(this).next("input.preco").val(); as it replaces the Number(preco) for Number(qtde) works, but I need you to be the Number(preco), clear-cut.

$('input').change(function() {
    var total = 0;
    $('input[type=checkbox]:checked').each(function() {
        var qtde = $(this).next("input").val();
        var preco = $(this).next("input.preco").val();
        total += Number(qtde) * Number(preco);
    });

    $('#total').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox[]"> 
<input type="number" value="1" min="1"> 
<input type="number" class="preco" value="8">
<br>
<input type="checkbox" name="checkbox[]"> 
<input type="number" value="1" min="1"> 
<input type="number" class="preco" value="24">
<br>
<input type="checkbox" name="checkbox[]"> 
<input type="number" value="1" min="1"> 
<input type="number" class="preco" value="17">
<br><br>
<span>Total:</span><input type="text" id="total" />

1 answer

3


Like the preco is the next input after the amount (qtde), you can use the next based on it, example:

var preco = $(this).next("input").next(".preco").val();

See the full code:

$('input').change(function() {
    var total = 0;
    $('input[type=checkbox]:checked').each(function() {
        var qtde = $(this).next("input").val();
        var preco = $(this).next("input").next(".preco").val();
        total += Number(qtde) * Number(preco);
    });

    $('#total').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox[]"> 
<input type="number" value="1" min="1"> 
<input type="number" class="preco" value="8">
<br>
<input type="checkbox" name="checkbox[]"> 
<input type="number" value="1" min="1"> 
<input type="number" class="preco" value="24">
<br>
<input type="checkbox" name="checkbox[]"> 
<input type="number" value="1" min="1"> 
<input type="number" class="preco" value="17">
<br><br>
<span>Total:</span><input type="text" id="total" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.