JSFiddle - React, Tailwind, and code Playground

by luizpaulo165

HTML

<form id="listForm">
    <input type="checkbox" name="choice" value="2" /> 2<br/>
    <input type="checkbox" name="choice" value="5" /> 5<br/>
    <input type="checkbox" name="choice" value="10" /> 10<br/>
    <input type="checkbox" name="choice" value="20" /> 20<br/>
</form>

<table>
    <th>
        <td><b>Total de:</b></td>
        <td id="total"></td>
    </th>
</table>

JavaScript

// variavel que irá armazenar a soma dos valores
var soma = 0;
// evento change no input de type checkbox
$('#listForm input[type=checkbox]').change(function(){
    var input = $(this),// input que é checada
        inputValue = parseInt(input.val()),// pega o valor do input e transforma de string para número
        totalElem = $('#total');// id do elemento onde será exibido o resultado
       
    // verificação do input, para saber se ele foi checado ou não
    if(input.is(':checked')){
        soma = soma + inputValue ;//caso tenha sido checado, ele soma 
    }else{
        soma = soma - inputValue;//caso contrario ele subtrai
    }
    
    // mostra o resultado final na tela
    totalElem.text(soma);
});