I made a function, which should check whether my input field, with type checkbox has been checked or not... but whenever I check my input field the input fields I wish to make required do not get the required attributes.
I basically tried everything from this topic: jQuery add required to input fields
and read this topic in hopes of finding something: .prop() vs .attr()
but unfortunately none of the topics has helped me much further. So either I made a mistake somewhere in my code, or the required attribute is a bit buggy.
I call the function via my input field (onclick event). I have already checked whether selectors were correct, and they are.
this is how my HTML looks like:
<div class="row" style="margin: auto;">
<div class="custom-control custom-checkbox col-md-4">
<input class="custom-control-input" onclick="is_required()" type="checkbox" id="fruittariër" value="fruittariër" name="vegetarisch[]">
<label class="custom-control-label" for="fruittariër"> fruittariër</label>
</div>
<div class="col-md-4 input-group leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">€</span>
</div>
<input type="number" step="0.01" class="form-control" placeholder="Kosten" name="vegCosts[]">
</div>
<div class="input-group col-md-4 leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="veganDatePicker"><i class="fas fa-calendar-alt"></i></span>
</div>
<input type="text" class="form-control" name="veganEindDatum[]" id="shutDateFruittariër" placeholder="Sluit Datum" aria-label="veganDatePicker" aria-describedby="veganDatePicker">
</div>
</div>
this is how I call my function:
<input class="custom-control-input" onclick="is_required()" type="checkbox" value="vegan" name="vegetarisch[]">
function is_required() {
//check whether the checkbox has been checked or not
//if yes, make the other input fields inside the row required
// variable odin = the row wrapped around the cols
$('input[name="vegetarisch[]"]').each(function(index, thisElement) {
if($(thisElement).is(':checked')) {
let odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', true);
odin.find('input[name="veganEindDatum[]"]').attr('required', true);
} else {
odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', false);
odin.find('input[name="veganEindDatum[]"]').attr('required', false);
}
});
}
So what I wish to achieve: When the checkbox is checked I want to have the 2 other input fields inside the row to gain the attribute 'required'.