From 8f582892cd54f92f036713bd8fd5a27d04bfb550 Mon Sep 17 00:00:00 2001 From: Bartek Fabiszewski Date: Thu, 12 Dec 2019 15:26:13 +0100 Subject: [PATCH] Select default value after hiding 'all' option --- js/src/select.js | 15 ++++++++++++++- js/test/select.test.js | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/js/src/select.js b/js/src/select.js index 5804ceb..a19479d 100644 --- a/js/src/select.js +++ b/js/src/select.js @@ -22,11 +22,15 @@ export default class uSelect { /** * @param {HTMLSelectElement} element Select element * @param {string=} head Optional header text + * @param {string=} all Optional all option text */ - constructor(element, head) { + constructor(element, head, all) { this.element = element; this.hasAllOption = false; this.allText = ''; + if (all && all.length) { + this.allText = all; + } if (head && head.length) { this.head = head; } else { @@ -44,6 +48,10 @@ export default class uSelect { } } + get selected() { + return this.element.value; + } + /** * @param {string} text */ @@ -68,8 +76,13 @@ export default class uSelect { } hideAllOption() { + const isSelectedAll = this.selected === uSelect.allValue; this.hasAllOption = false; this.remove(uSelect.allValue); + if (isSelectedAll) { + this.selected = this.hasHead ? uSelect.headValue : ''; + this.element.dispatchEvent(new Event('change')); + } } addHead() { diff --git a/js/test/select.test.js b/js/test/select.test.js index 2d11e5a..b15a729 100644 --- a/js/test/select.test.js +++ b/js/test/select.test.js @@ -248,7 +248,7 @@ describe('Select tests', () => { 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].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', () => {