Search code examples
javascriptmaterial-designmaterial-design-lite

dynamically built input using MDL does not render correctly


I have the following code,

var loginForm = document.createElement('div');

loginForm.className = 'row';

loginForm.innerHTML = '<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo"><input class="mdl-textfield__input" type="text" id="login" /><label class="mdl-textfield__label" for="login">Username</label></div>';

document.getElementById('page-content').appendChild(loginForm);

The problem is that since the javascript functions have already ran the input is not styled correctly.

Does anyone what javascript function I need to call to make this work? I tried MaterialTextfield.prototype.init() but nothing changed.


Solution

  • You can use MDL's upgrading element function. Since you have created the loginForm dynamically, you can upgrade it in scope with

        componentHandler.upgradeElement(loginForm);
        //or, componentHandler.upgradeDom(loginForm);
        //however, I suggest using jQuery to upgrade multiple if you are adding more than one
        componentHandler.upgradeElements($('.mdl-textfield').get());
    

    This will get all the mdl-textfield objects and upgrade them (if not upgraded before)