[英]How do I make sure in JavaScript that when I click on any checkbox, the input field goes to 0
How do I make sure that when I click on any checkbox, the input field goes to 0. Because now it works with the first, but not with the others.我如何确保当我单击任何复选框时,输入字段变为 0。因为现在它适用于第一个,但不适用于其他复选框。
This is the code I have now:这是我现在的代码:
let checkbox = document.getElementById("abs");
let inp = document.getElementById("cijfer");
checkbox.addEventListener('change', function() {
if (this.checked) {
inp.value = 0;
}
});
The first input field does go to 0, but the second one does not.第一个输入字段将 go 变为 0,但第二个输入字段没有。
Picture of the problem:问题图片:
Checkbox and input code in gohtml: gohtml中的复选框和输入代码:
<td><input id="cijfer" type="number" name="grade-{{$s.ID}}" step="0.1" min = "0" max = "10" value="{{(index $.Grades $s.ID).Value}}"></td>
<td>
<input id="abs" type="checkbox" name="abs-{{$s.ID}}">
<label for="abs">ABS</label>
</td>
you are using id
( getElementById
) and it's an unique attribute!您正在使用
id
( getElementById
),它是一个独特的属性!
use "abs" class and "cijfer" class instead!请改用“abs”class 和“cijfer”class!
then find the closest input and make the value zero!然后找到最接近的输入并将值设为零!
<script>
function closest(el, classname) {
if(el.parentNode){
if(el.parentNode.className.includes(classname)){
return el.parentNode;
}
else{
return closest(el.parentNode, classname);
}
}
else{
return false;
}
}
document.querySelectorAll('.abs').forEach(function(item) {
item.addEventListener('change', function() {
if (this.checked) {
let closest = closest(this, 'cijfer');
closest.value = "0";
}
}
});
</script>
this was pure js: you may use jquery instead:这是纯 js:您可以改用 jquery:
$('.abs').on('change', function(){
$(this).prev('input').val('0');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.