javascriptjquerymaterial-design-lite

How to display dynamic value in mdl menu select


I am trying to display the dynamic value fetched from the server in a mdl select value for the edit option. I am using jquery .val() for filling the value of the input tag. How even the data is not displayed in the select menu. Can anyone help me do it?

Here is the code I am using for displaying the select Menu:

<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select">
  <input type="text" value="" class="mdl-textfield__input" id="estream" readonly>
  <input type="hidden" value="" name="stream" id="estream2">
  <i class="mdl-icon-toggle__label material-icons" style="color: #fff;">keyboard_arrow_down</i>
  <label for="estream" class="mdl-textfield__label">Select Stream                                                                                                            </label>
  <ul for="estream" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
    <?php                                   
      foreach ($streams as $row) {
    ?>
    <li class="mdl-menu__item" data-val="<?php echo $row->Name; ?>">
      <?php echo $row->Name; ?>
    </li>
    <?php   
      }
    ?>
  </ul>
</div>

And here is how I am trying to update the value using jQuery:

$("#estream").val("lorem");

Solution

  • You don't need to set the input's value. Just to trigger click() on the right li.

    document.querySelector('button').addEventListener('click', () => {
      const valueToSet = 'BLR';
      const itemToSelect = document.querySelector(`.getmdl-select li[data-val=${valueToSet}]`)
      itemToSelect.click();
      
      console.log(document.querySelector('[name=sample1]').value);
    });
    <link rel="stylesheet" href="https://creativeit.github.io/getmdl-select/lib/material.min.css" />
    <link rel="stylesheet" href="https://creativeit.github.io/getmdl-select/getmdl-select.min.css" />
    
    <div class="mdl-textfield mdl-js-textfield getmdl-select">
      <input type="text" value="" class="mdl-textfield__input" id="sample1" readonly>
      <input type="hidden" value="" name="sample1">
      <label for="sample1" class="mdl-textfield__label">Country</label>
      <ul for="sample1" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
        <li class="mdl-menu__item" data-val="DEU">Germany</li>
        <li class="mdl-menu__item" data-val="BLR">Belarus</li>
        <li class="mdl-menu__item" data-val="RUS">Russia</li>
      </ul>
    </div>
    <script src="https://creativeit.github.io/getmdl-select/lib/material.min.js"></script>
    <script src="https://creativeit.github.io/getmdl-select/getmdl-select.min.js"></script>
    <hr />
    <button>Set selected</button>