I have several checkboxes in my table (unspecified number) and set a value of 2000
for each checkbox.
I want each check box that was checked to be multiplied by 2000
and if it was unchecked 2000
be deducted from the total amount?
For example, if 3 checkboxes are checked, the number 3 is multiplied by 2000
,3 * 2000
.
And if it is unchecked from this number, its value will be deducted from the total?
And display the total value in span
?
<table >
<thead>
<tr>
<th>
choose
</th>
</tr>
</thead>
<tbody>
@foreach (var item in listitem)
{
<tr>
<td>
<input type="checkbox" autocomplete="off" />
</td>
</tr>
}
</tbody>
total price :<span ></span>
CodePudding user response:
You can get the checked checkbox simply by using :checked
pseudo selector
const multiplier = 2000;
function getTotalPrice(){
const checkedCount = $('.check-horse:checked').length;
return checkedCount * multiplier;
}
$(document).on('change','.check-horse', e=> $('.totalprice').text(getTotalPrice());
It should work as expected.
CodePudding user response:
Details are commented in example below. Note, the value of each checkbox has been assigned as 2000. Also instead of a <span>
, an <output>
is used -- it is an inline tag and can contain text like a <span>
, but unlike the <span>
an <output>
can also have a value
like a form-control (ex. <input>
, <select>
, etc.).
/*
Whenever the user changes the state of any checkbox the event
handler chkSum(e) is invoked
*/
$(':checkbox').on('change', chkSum);
// Event handler is a function that listens for events
function chkSum(e) {
// Define a 0 value in outer scope
let total = 0;
// On each checkbox that's CHECKED...
$(':checkbox:checked').each(function() {
// Add the checkbox value (converted into a real number) to total
total = Number($(this).val());
});
/*
After iterations display total value
output.total can also use .val()
*/
$('.total').text(total);
};
<fieldset>
<output class='total'>0</output><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
<input type='checkbox' value='2000'><br>
</fieldset>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>