Jhonny Jr. Jhonny Jr. - 2 months ago 7
HTML Question

Check and summed if two or more checkbox is checked

I have an 4 input checkbox tag, and 1 div tag to display a price if one checkbox is checked

<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>


What i want to do if only 1 random checkbox is checked it will display number 1,800 on div#price, but if 2 checkbox is checked it will summed become 3,600 and so on until 4 checkbox. But i really confused how to do that using jQuery. Any idea?

Answer
  • Use :checkbox selector to assign change event on all thre type = checkbox elements, one can add [value="None"] while selecing checkbox elements to be more specific.
  • Use :checkbox:checked selector to select the checked checkboxes.

var val = 1800;
$(':checkbox[value="None"]').on('change', function() {
  var len = $(':checkbox:checked').length;
  $('#price').text(len * val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>