If no checkbox is selected, the form doesn’t allow sending.
I would like to create a rule like this for boxes. At least two boxes must be filled. Otherwise, the form should not be allowed to be sent.
Below is the code structure.
on JSfiddle
JS:
$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="control-group input-group"><div class="input-group mb-3"><div class="input-group-prepend"><div class="input-group-text"><input type="checkbox" name="corrects[]" value="' + x + '" aria-label="Checkbox for following text input"></div></div><input type="text" class="form-control" name="options[]" aria-label="Text input with checkbox"><div class="input-group-btn"><button class="btn btn-danger remove-camera" type="button"> Remove</button></div></div></div>'); //add input box
}
});
$(wrapper).on("click", ".remove-camera", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
})
$('#submit-btn').click(() => {
const x = document.querySelector('.cameras').querySelectorAll('input[type="text"]')
const checkedInputs = Array.from(x).filter(input => input.valueOf()).length
if (checkedInputs < 2) {
alert('at least 2 inpouts must be filled')
return;
}
const xd = document.querySelector('.cameras').querySelectorAll('input[type="checkbox"]')
const checkedBoxes = Array.from(xd).filter(input => input.checked).length
if (checkedBoxes < 1) {
alert('at least one checkbox must be checked')
return;
}
alert(`you checked ${checkedBoxes} checkboxes`)
})
});
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cameras">
<div class="camera-field">
<button type="button" class="add-camera btn btn-primary">+ Add Camera
</button>
</div>
<div class="control-group input-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" name="corrects[]" value="1" aria-label="Checkbox for following text input">
</div>
</div>
<input type="text" class="form-control" name="options[]" aria-label="Text input with checkbox">
<div class="input-group-btn">
</div>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-4">
<button type="submit" class="btn btn-primary" id="submit-btn">submit</button>
<div class="mt-2">
</div>
</div>
Thank you @jenovs for helping with the development of the code.