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.
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.
Picture of the problem:
Checkbox and input code in 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!
use "abs" class and "cijfer" class instead!
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:
$('.abs').on('change', function(){
$(this).prev('input').val('0');
});