CreativeIT / getmdl-select

Select for material-design-lite
http://creativeit.github.io/getmdl-select/
MIT License
301 stars 87 forks source link

How to pre-select a value dynamically? #101

Closed FANMixco closed 5 years ago

FANMixco commented 5 years ago

My question is more related to is it possible more than a bug, let's take the basic example:

    <!-- Simple Select -->
    <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>

http://creativeit.github.io/getmdl-select/

How could I select a value after it's loaded? Because I can see it's possible to do it before with data-selected="true":

    <!-- Simple Select -->
    <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" data-selected="true">Belarus</li>
            <li class="mdl-menu__item" data-val="RUS">Russia</li>
        </ul>
    </div>

But I cannot find how to re-select it after it's done, I tried something like this with jQuery: $($('.mdl-menu__item')[1]).data("selected", "true")

Thanks for any idea.

mikhail commented 5 years ago

What's the solution here? doing $('#sample1').val('NewValue') creates a resetting behavior for the dropdown.

My approach:

$('...selector for your <li> item').click()

This invokes all the changed .data(), .val() and .className changes that needed to be done

FANMixco commented 5 years ago

What's the solution here? doing $('#sample1').val('NewValue') creates a resetting behavior for the dropdown.

My approach:

$('...selector for your <li> item').click()

This invokes all the changed .data(), .val() and .className changes that needed to be done

https://stackoverflow.com/a/55190641/2889347