How to serialize a form with checkbox [closed]

-1

In this script it calculates the total values of checked checkboxes, which adaptation would be necessary in addition to the sum it also show the name and value attributes of the respective checked checkboxes?

HTML:    

<inputtype="checkbox" name="teste" checked="" value="20.00" />
    <input type="checkbox" name="teste" checked="" value="20.00" />
    <input type="checkbox" name="teste" checked="" value="20.00" />
    <input type="checkbox" name="teste" checked="" value="20.00" />

    <div id='resultado_soma'>
        <?echo $total?>
    </div>
    <!--Resultado da soma dos 
 checkbox-->
    <div id='resultado_soma_menos_variavel'>
        <?echo $total_geral?>
    </div>
    <!-- 
 Resultado Pegando      
 a Variavel - Resultado checkbox -->

JavaScript:

(function() {
    var elements = document.getElementsByTagName('input');
    var resultado = document.getElementById('resultado_soma');
    for (var i = 0; i < elements.length; i++) {
        elements[i].addEventListener('change', calcular);
    }

    function calcular() {
        var dados = [].map.call(elements, function(input) {
            return {
            el: input,
                value: parseInt(input.value),
                name: input.name
            };
        });
        var total = dados.reduce(function(soma, el) {
            return soma + (el.el.checked ? el.value : 0);
        }, 0);

        resultado.innerHTML = JSON.stringify(dados) + ' ' + total;
    }
})();
    
asked by anonymous 02.01.2016 / 14:36

1 answer

2

I do not know if I understand correctly, but take a look at it:

First, give a DIFFERENT name for each checkbox: test1, test2, test3 etc ...

<input type="checkbox" name="teste1" value="20.00" />
<input type="checkbox" name="teste2" value="20.00" />
<input type="checkbox" name="teste3" value="20.00" />
<input type="checkbox" name="teste4" value="20.00" />

Then, where you have:

resultado.innerHTML = JSON.stringify(dados) + ' ' + total;

Switch to:

//resultado.innerHTML = JSON.stringify(dados) + ' ' + total;
   resultado.innerHTML = $("#form").serialize().replace(/&/g, '<br />') + '<br /><br />R$ ' + total.toFixed(2).replace(".",",");

See that I commented the first line (the one I had before) because I do not know what you want to do with it.

Test here on this Fiddle: link

    
02.01.2016 / 21:06