fradrive/static/js/reactive_input.js

69 lines
2.1 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function() {
if (!window.utils) {
window.utils = {};
}
// makes <label> smaller if <input> is focussed
window.utils.reactiveInputLabel = function(input, label) {
input.addEventListener('focus', function() {
label.classList.add('small');
});
label.addEventListener('click', function() {
label.classList.add('small');
input.focus();
});
input.addEventListener('blur', function() {
if (input.value.length < 1) {
label.classList.remove('small');
}
});
};
Array.from(document.querySelectorAll('.reactive-label')).forEach(function(label) {
var input = document.querySelector('#' + label.getAttribute('for'));
window.utils.reactiveInputLabel(input, label);
});
// registers input-listener for each element in <elements> (array) and
// enables <button> if <fn> for these elements returns true
window.utils.reactiveButton = function(elements, button, fn) {
if (elements.length == 0) {
return false;
}
var checkboxes = elements[0].getAttribute('type') === 'checkbox';
var eventType = checkboxes ? 'change' : 'input';
updateButtonState();
elements.forEach(function(el) {
el.addEventListener(eventType, function() {
updateButtonState();
});
});
function updateButtonState() {
if (fn.call(null, elements)) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', 'true');
}
}
};
// auto reactiveButton submit-buttons with required fields
var forms = document.querySelectorAll('form');
Array.from(forms).forEach(function(form) {
var requireds = form.querySelectorAll('[required]');
var submitBtn = form.querySelector('[type=submit]');
window.utils.reactiveButton(Array.from(requireds), submitBtn, function(inputs) {
var done = true;
inputs.forEach(function(inp) {
var len = inp.value.trim().length;
if (done && len === 0) {
done = false;
}
});
return done;
});
});
});