fix: select first enabled option by default when initial value is undefined (#8331)

Fixes an unintended regression introduced in #6170.

Fixes #7041
pull/8335/head
Theodore Brown 1 year ago committed by GitHub
parent 69c199feac
commit 8cf037c904
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -567,8 +567,16 @@ export function select_options(select, value) {
}
}
function first_enabled_option(select) {
for (const option of select.options) {
if (!option.disabled) {
return option;
}
}
}
export function select_value(select) {
const selected_option = select.querySelector(':checked') || select.options[0];
const selected_option = select.querySelector(':checked') || first_enabled_option(select);
return selected_option && selected_option.__value;
}

@ -5,6 +5,7 @@ export default {
<p>selected: a</p>
<select>
<option disabled='' value='x'>x</option>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
@ -18,7 +19,8 @@ export default {
const select = target.querySelector('select');
const options = [...target.querySelectorAll('option')];
// first enabled option should be selected
assert.equal(select.value, 'a');
assert.ok(options[0].selected);
assert.ok(options[1].selected);
}
};

@ -5,6 +5,7 @@
<p>selected: {selected}</p>
<select bind:value={selected}>
<option disabled>x</option>
<option>a</option>
<option>b</option>
<option>c</option>

@ -56,5 +56,40 @@ export default {
<p>selected: d</p>
`);
component.selected = 'b'; // second option should now be selected
assert.equal(select.value, 'b');
assert.ok(options[1].selected);
assert.htmlEqual(target.innerHTML, `
<p>selected: b</p>
<select>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>
<p>selected: b</p>
`);
component.selected = undefined; // also doesn't match an option
// now no option should be selected again
assert.equal(select.value, '');
assert.equal(select.selectedIndex, -1);
assert.ok(!options[0].selected);
assert.htmlEqual(target.innerHTML, `
<p>selected: undefined</p>
<select>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>
<p>selected: undefined</p>
`);
}
};

Loading…
Cancel
Save