Dima Vleskov - 1 year ago 109
Javascript Question

# how to calculate numbers of checked checkbox using javascript(jquery)

how can i calculate this numbers, i need that the result of first column adds (400 + 700) in one field(counter-one) and the second column (300 + 800) in other(counter-two). The result

``````<tr>
<td><span class="cost">400</span>&nbsp;грн.</td>
<td><span class="cost">300</span>&nbsp;грн./месяц</td>
<td>
<label class="switch">
<input type="checkbox" id="cost-one">
<div class="slider round"></div>
</label>
</td>
</tr>
<tr>
<td><span class="cost">700</span>&nbsp;грн.</td>
<td><span class="cost">800</span>&nbsp;грн./месяц</td>
<td>
<label class="switch">
<input type="checkbox" id="cost-two>
<div class="slider round"></div>
</label>
</td>
</tr>
``````

html:

``````<div class="counter-wrapper">
<div class="install">
<p class="counter-one">0&nbsp;<span class="currency">грн.</span></p>
</div>
<div class="monitoring">
<p class="counter-two">0&nbsp;<span class="currency">грн./месяц</span></p>
</div>
</div>
``````

• Select the checked inputs
• Get cost numbers related to selected inputs
• Get the some of the cost numbers obtained

``````\$("button").on("click", function() {
var costs = \$("input:checked").parents("tr").find(".cost"); //get .cost elements of the checked inputs

var total =
\$.map(costs, function(i, v) { return parseInt(\$(i).text()); }) //get an array of cost numbers
.reduce(function(preval, cval) { return preval + cval }, 0); //get the sum of cost numbers

console.log(total);
});``````
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Calculate</button>
<hr/>

<table>
<tr>
<td><span class="cost">400</span>&nbsp;грн.</td>
<td><span class="cost">300</span>&nbsp;грн./месяц</td>
<td>
<label class="switch">
<input type="checkbox" id="cost-one" />
<div class="slider round"></div>
</label>
</td>
</tr>
<tr>
<td><span class="cost">700</span>&nbsp;грн.</td>
<td><span class="cost">800</span>&nbsp;грн./месяц</td>
<td>
<label class="switch">
<input type="checkbox" id="cost-two" />
<div class="slider round"></div>
</label>
</td>
</tr>
</table>

<div class="counter-wrapper ">
<div class="install ">