I have an xml coming from sql server which is rendered by my XSL script. I am using the latest release of Material Components for the Web and the problem I have is that I don't seem to be able to set options in select menus via JS. Here is my mdc-select:
<div id="bridgeSizeSelect" name="bridgeSize" class="mdc-select" role="listbox" data-mdc-auto-init="MDCSelect" style="width:22%;">
<div class="mdc-select__surface mdc-ripple-upgraded" tabindex="0" style="width: 141px; --mdc-ripple-fg-size:100.2px; --mdc-ripple-fg-scale:1.8576761430946644;">
<div class="mdc-select__label">Bridge Size</div>
<div class="mdc-select__selected-text"></div>
<div class="mdc-select__bottom-line"></div>
</div>
<div class="mdc-menu mdc-select__menu">
<ul class="mdc-list mdc-menu__items">
<li class="mdc-list-item" role="option" id="XS" tabindex="0">
XS: <28 feet
</li>
<li class="mdc-list-item" role="option" id="S" tabindex="0">
S: 28-35 feet
</li>
<li class="mdc-list-item" role="option" id="M" tabindex="0">
M: 36-41 feet
</li>
<li class="mdc-list-item" role="option" id="ML" tabindex="0">
ML: 42-50 feet
</li>
<li class="mdc-list-item" role="option" id="L" tabindex="0">
L: 51-58 feet
</li>
<li class="mdc-list-item" role="option" id="XL" tabindex="0">
XL: 59-70 feet
</li>
<li class="mdc-list-item" role="option" id="XXL" tabindex="0">
XXL: 71-80 feet
</li>
<li class="mdc-list-item" role="option" id="XXXL" tabindex="0">
XXXL: >80 feet
</li>
</ul>
</div>
</div>
I have tried using the following JS:
const select = new mdc.select.MDCSelect(document.querySelector("#bridgeSizeSelect"));
select.value="<xsl:value-of select="Bridge_Size"/>";
where xsl:value-of select="Bridge_Size" can takes values like "XS", "S", etc but nothing happens.
I have also tried:
$("#bridgeSizeSelect").value="<xsl:value-of select="Bridge_Size"/>";
since my select is initialized when I load the page but again nothing happens. Finally, I have tried:
var bridgeSelect=document.querySelector("#bridgeSizeSelect");
var bridgeSelectInit = new mdc.select.MDCSelect(bridgeSelect);
bridgeSelectInit.value="<xsl:value-of select="Bridge_Size"/>";
with no luck. Any help would be greatly appreciated!
The mdc-select
element has a couple of ways to set the selected value. One option is to set the value before the select is initialized by adding the aria-selected
attribute to the html element you want selected.
https://codepen.io/williamernest/pen/xYabNq
Another option is to use selectedIndex
to indicate which value should be selected after the select has been initialized.
https://codepen.io/williamernest/pen/xYaboq
There's currently a bug where you have to add mdc-select__label--float-above
to the label if pre-selecting an option, but that should be fixed soon.