From ace6bc0354b3df8aa1f373ea1eb133ab68d3a3af Mon Sep 17 00:00:00 2001 From: raivaibhav Date: Sat, 23 Oct 2021 01:27:34 +0530 Subject: [PATCH] Fix: regression in option selected This add the selected attr to the dom element and later using the hasAttribute it check if any of the option have selected atrribute then don't set selectedIndex to -1, this way it avoid setting the selectedIndex on mount Fixes: https://github.com/sveltejs/svelte/issues/6873 --- .../compile/render_dom/wrappers/Element/Attribute.ts | 8 ++++++++ src/runtime/internal/dom.ts | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts b/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts index 3f57d004be..775a36fc56 100644 --- a/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts +++ b/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts @@ -140,6 +140,14 @@ export default class AttributeWrapper extends BaseAttributeWrapper { block.chunks.hydrate.push( b`${element.var}.${property_name} = ${init};` ); + const is_selected = property_name === 'selected'; + const is_boolean = typeof init.value === 'boolean'; + const attr_val = is_boolean ? x`""` : init; + if (is_selected) { + block.chunks.hydrate.push( + b`${method}(${element.var}, "${name}", ${attr_val});` + ); + } updater = block.renderer.options.dev ? b`@prop_dev(${element.var}, "${property_name}", ${should_cache ? this.last : value});` : b`${element.var}.${property_name} = ${should_cache ? this.last : value};`; diff --git a/src/runtime/internal/dom.ts b/src/runtime/internal/dom.ts index eb3389e3f8..4aafcc0467 100644 --- a/src/runtime/internal/dom.ts +++ b/src/runtime/internal/dom.ts @@ -534,16 +534,17 @@ export function set_style(node, key, value, important) { } export function select_option(select, value) { + let have_select_attr = false; for (let i = 0; i < select.options.length; i += 1) { const option = select.options[i]; - + if (option.hasAttribute('selected')) have_select_attr = true; if (option.__value === value) { option.selected = true; return; } } - select.selectedIndex = -1; // no option should be selected + if (!have_select_attr) select.selectedIndex = -1; // no option should be selected } export function select_options(select, value) {