Sometimes, you work within the constraints of an existing application, trying to change as little as possible. So when a client had a very simple (two field) form, that showed up as a Bootstrap modal, and I needed to make sure the user didn’t click the submit button until they filled out all the fields, I simply dropped in the following JavaScript.
$(document).on('change keyup', '[required]', function() {
var targetForm = $($('[required]')[0].form);
var requiredOk = targetForm.find('[required]').filter(function () { return $(this).val().length == 0; }).length == 0;
targetForm.find(':submit').prop('disabled', !requiredOk);
});
I then marked up my form fields by adding required
property to each field that was required to be true. A simplified example follows.
<form id="form1">
<input type="text" id="input1" required /><br />
<textarea id="textarea1" required></textarea><br />
<button type="submit" disabled>
Submit
</button>
</form>
Now, your submit buttons will automatically disable/enable. It doesn’t work in more complex forms with other field types, but I did start off by saying this was a “simple” solution, after all.
JSFiddle here: https://jsfiddle.net/05wyu3az/