Overview
I'm currently working on a project that involves a Register page. I'm using bootstrap and javascript/jquery on the client side.
The Problem
I don't want the user to submit the form until he fill each input field and check a checkbox. By default the submit button is disabled. I succeeded in activating the submit button when the fields are not empty. However my problem lies within checkbox, activating the submit button when the input fields are not empty and the checkbox checked.
This is a code snippet to better clarify my problem (eliminating unnecessary fields for this problem)
$(document).ready(function() {
$('.register input').keyup(function() {
var empty = false;
$('.register input').each(function() {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- username input -->
<div class="form-outline mb-4 register">
<input type="text" id="registerUsername" class="form-control" />
<label class="form-label" for="registerUsername">Username</label>
</div>
<!-- Password input -->
<div class="form-outline mb-4 register">
<input type="password" id="registerPassword" class="form-control" />
<label class="form-label" for="registerPassword">Password</label>
</div>
<!-- Checkbox -->
<div class="form-check d-flex justify-content-center mb-4">
<input class="form-check-input me-2" type="checkbox" value="" id="registerCheck" aria-describedby="registerCheckHelpText" />
<label class="form-check-label" for="registerCheck">
I have read and agree to the terms
</label>
</div>
<!-- Submit button -->
<button type="submit" id="register" disabled="disabled" class="btn btn-dark btn-block mb-3">Register</button>
What have I tried?
Well, I came to answers on Stackoverflow and tried adjusting them to my need. Below are two solutions I tried and their flaws. Unfortunately, It didn't work as expected.
- I tried checking if checkbox is checked just like I did with the input fields (I forgot the source for this one)
Here is the code I used:
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).is(":not(:checked)")){
$('#register').attr('disabled', 'disabled');
}
});
});
- The second approach was from this answer. This also didn't work :(
Any help is appreciated. Thanks in advance.