Count checked checkboxes and perform operation

Asked

Viewed 36 times

-2

I have the following codes: the first checkbox is equivalent to the additional ones that are worth 2 real and the second to those that are worth 4 real.

Additional 2 reais:

<input type="checkbox" />Morango
<input type="checkbox" />Ninho
<input type="checkbox" />Uva

Additional 4 reais:

<input type="checkbox" />Nutella
<input type="checkbox" />Bis
<input type="checkbox" />Kit Kat

Through javascript, how can I count how many checkboxes were selected in the extra 2 real and count how many were selected in the additional 4 real and add the results of the two counts?

Note: It will not be necessary to codar for me, just say what I can do, but if you want, feel free...

1 answer

1


You can simply count using a selector that selects checkbox type input that is "checked", like this:

document.querySelectorAll('input[type="checkbox"]:checked').length

It turns out that in your case there is no way to distinguish between the R$2 checkbox and the R$4 checkbox, so I suggest using a class, or name to distinguish:

document
  .getElementById("contar")
  .addEventListener("click", function(){
    var doisReais = document.querySelectorAll('input[name="dois"][type="checkbox"]:checked').length;

    var quatroReais = document.querySelectorAll('input[name="quatro"][type="checkbox"]:checked').length;

    var total = (doisReais * 2) + (quatroReais * 4);

    console.log("Total de R$2: " + doisReais);
    console.log("Total de R$4: " + quatroReais); 
    console.log("Total: R$" + total);
});
Adicionais de 2 reais:
<input name="dois" type="checkbox" />Morango
<input name="dois" type="checkbox" />Ninho
<input name="dois" type="checkbox" />Uva
<br/>
Adicionais de 4 reais:

<input name="quatro" type="checkbox" />Nutella
<input name="quatro" type="checkbox" />Bis
<input name="quatro" type="checkbox" />Kit Kat

<br />
<button id="contar">Contar</button>

  • +1 "... and sum up the results of the two counts?" I think I missed the total count of the real ones

  • truth @Cmtecardeal, added the general sum :)

  • THANK YOU!!!! You helped me and taught me a simple way to do it. Thank you!

  • @Vieirabraz don’t forget to accept the answer if it helped you :)

  • I’m new on this site, I don’t know how to do this... I’ll be trying and looking

Browser other questions tagged

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