因此,我尝试根据按钮是否被点击,将每行总和加 2。
HTML:
<table>
<tr>
<td>
<input type="checkbox" class="prof" name="prof" value="0">
<input class="mod" name="mod" type="text" value='2'>
<input class="savings" name="savings" type="text">
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="prof" name="prof" value="0">
<input class="mod" name="mod" type="text" value='4'>
<input class="savings" name="savings" type="text">
</td>
</tr>
</table>
j查询:
//when document is ready, have numbers appear in each '.savings'
$(document).ready(function() {
//on button click, change the number depending on if checked or not
$('input[type="checkbox"]').click(function() {
if ($('input[type="checkbox"]').prop("checked") == true) {
$('tr').each(function() {
var sum = 2
$(this).find('.mod').each(function() {
var mod = $(this).val();
if (!isNaN(mod) && mod.length !== 0) {
sum += parseFloat(mod);
}
});
$('.savings', this).val(sum);
})
} else {
$('tr').each(function() {
var sum = 0
$(this).find('.mod').each(function() {
var mod = $(this).val();
if (!isNaN(mod) && mod.length !== 0) {
sum += parseFloat(mod);
}
});
$('.savings', this).val(sum);
})
}
})
});
我的问题是单击按钮会向每一行添加两个,而不是它所在的行。 任何帮助将不胜感激。
最佳答案
你可以试试这个:
$('input[type="checkbox"]').click(function() {
var mod = $(this).next('.mod').val();
var sum = ($(this).is(":checked")) ? 2 : 0;
if (!isNaN(mod) && mod.length !== 0) {
sum += parseFloat(mod);
}
$(this).siblings('.savings').val(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="checkbox" class="prof" name="prof" value="0">
<input class="mod" name="mod" type="text" value='2'>
<input class="savings" name="savings" type="text">
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="prof" name="prof" value="0">
<input class="mod" name="mod" type="text" value='4'>
<input class="savings" name="savings" type="text">
</td>
</tr>
</table>
关于javascript - 如何根据按钮单击添加两个每行总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64067832/