Skip to content

Instantly share code, notes, and snippets.

@lucasmazza
Last active September 16, 2015 01:43
Show Gist options
  • Save lucasmazza/f33b82f4f996ec5dffcc to your computer and use it in GitHub Desktop.
Save lucasmazza/f33b82f4f996ec5dffcc to your computer and use it in GitHub Desktop.
DisabledButtonElement
const slice = Array.prototype.slice;
// Public: Custom `button` element that is enabled and disabled based on the
// validity state of the inputs inside the same 'form' element as the button.
//
// Example
//
// <form>
// <input name='name' required />
// <button is='disabled-button'>Click me after you fill in the input</button>
// </form>
const DisabledButton = {
attachedCallback() {
this._form = this._findForm(this);
this._keyUpCallback = this._update.bind(this);
this._form.addEventListener('keyup', this._keyUpCallback, false);
this._keyUpCallback();
},
detachedCallback() {
this._form.removeEventListener('keyup', this._keyUpCallback);
},
_update() {
let inputs = this._findInputs(this._form);
if (inputs.every(input => input.checkValidity())) {
this.removeAttribute('disabled');
} else {
this.setAttribute('disabled', true);
}
},
_findInputs(form) {
let inputs = slice.call(form.getElementsByTagName('input'), 0);
return inputs.filter(input => input.type !== 'hidden');
},
_findForm(element) {
if (element.nodeName === 'FORM') {
return element;
} else {
return this._findForm(element.parentElement);
}
}
};
const DisabledButtonPrototype = Object.create(HTMLButtonElement.prototype);
Object.keys(DisabledButton).forEach(prop => {
DisabledButtonPrototype[prop] = DisabledButton[prop];
});
window.DisabledButtonElement = document.registerElement('disabled-button', {
prototype: DisabledButtonPrototype,
'extends': 'button'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment