Tags: JS
Here's a little song I wrote... About disabling the input button until all required fields have a value. This particular form has a few checkboxes and some text typed inputs.
First, let's get an array with all the empty elements. Except excluded ones (you can add them to the variable, or you can pass an array as a parameter).
/**
* Create an array of empty fields
************************************************************************************/
function getEmptyFields(ignored = []) {
var defaultIgnored = ['address2'];
var ignoreFields = ignored.concat(defaultIgnored);
return $('.modal-body').find("input").filter(function() {
if (-1 == $.inArray($(this).attr('name'), ignoreFields)) {
if ($(this).is(':checkbox')) {
var noValue = ! this.checked;
} else {
var noValue = this.value === "";
}
return noValue;
}
});
}
Now, define what happens if all fields have values. jQuery doesn't have a native toggle attribute function, so we have to do it with a simple if / else statement:
/**
* Toggle submit button based on empty fields
************************************************************************************/
function toggleSubmitButton(emptyFields) {
if(emptyFields.length == 0) {
$('.btn-success').removeAttr('disabled');
} else {
$('.btn-success').attr('disabled', 'disabled');
}
}
Finally, bind it to the 'change' event on all inputs. Voila, the button is enabled and disabled when needed.
/**
* Bind enable submit button to input change
************************************************************************************/
$('input').off('change');
$('input').on('change', function () {
toggleSubmitButton(getEmptyFields());
});
©2023, kirillsimin.com