1

i wanted to select a particular option while construction of dropdown.

Question: i want to select grapes while construction of dropdown. not after construction.

Note: i want to construct it at once(while appending). don't want to select after construction.

$(function(){
   var listOptions = ['apple','banana','grapes']

 var optionsStr = '';
 for(var i = 0; i < listOptions.length; i++){
    var selectedClass = '',ariaValue = '', value = '';
    value = listOptions[i];
    if(value == 'grapes') selectedClass = 'mdc-list-item--selected',ariaValue = 'aria-selected="true"';
    optionsStr += `<li class="mdc-list-item ${selectedClass}" ${ariaValue} data-value="" role="option">
        <span class="mdc-list-item__ripple"></span>
          <span class="mdc-list-item__text">
           ${listOptions[i]}
        </span>
      </li>`
}
$('#foods_items').html(optionsStr);

mdc.select.MDCSelect.attachTo(document.querySelector('.mdc-select'));

});
<head>
  <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
    <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>

</head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 
 <div class="mdc-select mdc-select--filled demo-width-class">
  <div class="mdc-select__anchor"
       role="button"
       aria-haspopup="listbox"
       aria-expanded="false"
       aria-labelledby="demo-label demo-selected-text">
    <span class="mdc-select__ripple"></span>
    <span id="demo-label" class="mdc-floating-label">Pick a Food Group</span>
    <span class="mdc-select__selected-text-container">
      <span id="demo-selected-text" class="mdc-select__selected-text">sss</span>
    </span>
    <span class="mdc-select__dropdown-icon">
      <svg
          class="mdc-select__dropdown-icon-graphic"
          viewBox="7 10 10 5" focusable="false">
        <polygon
            class="mdc-select__dropdown-icon-inactive"
            stroke="none"
            fill-rule="evenodd"
            points="7 10 12 15 17 10">
        </polygon>
        <polygon
            class="mdc-select__dropdown-icon-active"
            stroke="none"
            fill-rule="evenodd"
            points="7 15 12 10 17 15">
        </polygon>
      </svg>
    </span>
    <span class="mdc-line-ripple"></span>
  </div>

  <div class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth">
    <ul class="mdc-list" role="listbox" aria-label="Food picker listbox" id="foods_items">

    </ul>
  </div>
</div>

Please help me thanks in advance!!

Learner
  • 61
  • 2
  • 21

0 Answers0