Select default value after hiding 'all' option

This commit is contained in:
Bartek Fabiszewski 2019-12-12 15:26:13 +01:00
parent e8c1641f3f
commit 8f582892cd
2 changed files with 15 additions and 2 deletions

View File

@ -22,11 +22,15 @@ export default class uSelect {
/** /**
* @param {HTMLSelectElement} element Select element * @param {HTMLSelectElement} element Select element
* @param {string=} head Optional header text * @param {string=} head Optional header text
* @param {string=} all Optional all option text
*/ */
constructor(element, head) { constructor(element, head, all) {
this.element = element; this.element = element;
this.hasAllOption = false; this.hasAllOption = false;
this.allText = ''; this.allText = '';
if (all && all.length) {
this.allText = all;
}
if (head && head.length) { if (head && head.length) {
this.head = head; this.head = head;
} else { } else {
@ -44,6 +48,10 @@ export default class uSelect {
} }
} }
get selected() {
return this.element.value;
}
/** /**
* @param {string} text * @param {string} text
*/ */
@ -68,8 +76,13 @@ export default class uSelect {
} }
hideAllOption() { hideAllOption() {
const isSelectedAll = this.selected === uSelect.allValue;
this.hasAllOption = false; this.hasAllOption = false;
this.remove(uSelect.allValue); this.remove(uSelect.allValue);
if (isSelectedAll) {
this.selected = this.hasHead ? uSelect.headValue : '';
this.element.dispatchEvent(new Event('change'));
}
} }
addHead() { addHead() {

View File

@ -248,7 +248,7 @@ describe('Select tests', () => {
expect(select.element.options[1].text).toBe(options[0].listText); expect(select.element.options[1].text).toBe(options[0].listText);
expect(select.element.options[2].value).toBe(options[1].listValue); expect(select.element.options[2].value).toBe(options[1].listValue);
expect(select.element.options[2].text).toBe(options[1].listText); expect(select.element.options[2].text).toBe(options[1].listText);
expect(select.element.options[2].selected).toBe(true); expect(select.element.options[0].selected).toBe(true);
}); });
it('should remove option from select elements', () => { it('should remove option from select elements', () => {