Я использовал имя, начинающееся с cr_dr, так как у них нет класса
Я изменил вывод в поле ввода и изменил .text на .val для него на основе вашего wi sh, чтобы отправить его
<input type="text" id="sum" name="sum" value="0" />
$("#sum").val(sum.toFixed(2))
const calculateSum = function() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
let val = isNaN(this.value) || this.value.trim().length === 0 ? 0 : +this.value; // cast to number
const drcr = $(this).closest("tr").find("[name^=cr_dr]").val(); // name begins with cr_dr
sum += val * (drcr === "-" ? -1 : 1); // ternary based on the value
$(this).toggleClass("neg",drcr === "-"); // remove if you do not want this
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum")
.val(sum.toFixed(2))
.toggleClass("neg",sum<0); // remove if you do not want this
}
$(function() {
$(".txt").on("input", calculateSum);
$("select").on("change", calculateSum);
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
style="width:40%"
}
th,
td {
padding: 1px;
text-align: left;
}
.wrapper {
text-align: center;
}
.button {
position: absolute;
left: 400px;
background-color: #4CAF50;
border: 1px solid green;
color: white;
padding: 10px 32px;
text-align: center;
text-decoration: none;
font-size: 20px;
cursor: pointer;
width: 150px;
display: block;
}
.neg { color:red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:60%">
<caption>Tally Ledgers</caption>
<tr>
<th width="60">Head</th>
<th width="5">DR/CR</th>
<th width="15">Amount</th>
</tr>
<tr>
<td><input class="tally" type="tally" id="tally" name="tally" placeholder="tally"></td>
<td>
<select id="cr_dr" name="cr_dr">
<option value="">Select Credit Or Debit</option>
<option value="+">CR</option>
<option value="-">DR</option>
</select>
</td>
<td width="15"><input class="txt" type="text" id="amount" name="amount" placeholder="Amount"></td>
</tr>
<tr>
<td><input class="tally1" type="tally1" id="tally1" name="tally1" placeholder="tally1"></td>
<td>
<select id="cr_dr1" name="cr_dr1">
<option value="">Select Credit Or Debit</option>
<option value="+">CR</option>
<option value="-">DR</option>
</select>
</td>
<td width="15"><input class="txt" type="text" id="amount1" name="amount1" placeholder="Amount1"></td>
</tr>
<tr id="summation">
<td> </td>
<td align="right">Total :</td>
<td align="center"><input type="text" id="sum" name="sum" value="0" /></td>
</tr>
</table>