Imagine a newsletter subscription form. I have the form with just two different field types (text
, checkbox
), some of them need to be complete before submission. For sure, the required email field and at least one from the checkboxes. The submit/subscribe button should stay disabled until the condition from above is fulfilled. It also should revert from enabled to disabled state when the fields with values get empty.
I know this kind of question has been answered here a few times already. I went through some examples from previous questions of this functionality working with radios and checkboxes or <input>
fields only:
- Disabling submit button until all fields have values
- Disable submit button until all form inputs have data
Some of them are answered but used code is outdated. Moreover, I'm not able to make a working code for my specific case. Quite close was Disable submit button with jQuery until all fields have values (input, radio, select, checkbox). I used them all to make it to as far as here: I can count a number of filled fields and enable the button when at least two of them are completed. However, two checkboxes (without the email) are enough - which is wrong. Can you please help me?
$(function() {
$('.subscribe-form').on('input',':input',function() {
var inputs = $('.subscribe-form :input');
var num_inputs = inputs.length;
var num_filled = inputs.filter(function() { return $(this).is(':checkbox')?$(this).is(':checked'):!!this.value }).length;
$('.subscribe-form :submit').prop('disabled',(num_filled+1<num_inputs));
});
});
.subscribe-form {
width: 400px;
margin: 50px;
}
.subscribe-form__row {
padding: 0 0 10px;
margin: 0 0 10px;
border-bottom: 1px solid grey;
}
p {
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="subscribe-form">
<div class="subscribe-form__row">
<p>E-mail</p>
<input type="text" placeholder="your e-mail" />
</div>
<div class="subscribe-form__row">
<p>Interests</p>
<label for="checkbox-1">Nature</label>
<input id="checkbox-1" type="checkbox" />
<label for="checkbox-2">Travel</label>
<input id="checkbox-2" type="checkbox" />
</div>
<input type="submit" value="Subscribe" disabled />
</fieldset>