Search code examples
javascriptjquerymaterialize

Generate Materialize select on button click


I am trying to create a number of select forms when the user clicks a button. I am having some trouble initializing my select forms when the button is clicked.

So far I have tried:

$(document).ready(function() {

  $('select').material_select(); //This should initialize
  let output = {
    columnNumber: []
  };
  //let headers=[];
  let addColumnSource = $("#addColumnTemplate").html();
  let addColumnTemplate = Handlebars.compile(addColumnSource);

  $("#newColumnsButton").click(function() {
    $('select').material_select(); //Re-initialize after the button is clicked?
    for (let i = 1; i <= $("#numberOfColumns").val(); i++) {
      output.columnNumber.push(i);

    }
    $("#addColumnContainer").append(addColumnTemplate(output));

  });
$('select').material_select(); //Still not getting initialized 

});

And:

$("#newColumnsButton").click("contentChanged", function() {

    for (let i = 1; i <= $("#numberOfColumns").val(); i++) {
      output.columnNumber.push(i);

    }
    $("#addColumnContainer").append(addColumnTemplate(output));
    $('select').on('contentChanged', function() {
      // re-initialize (update)
      $(this).material_select();
    });
  });

But the select forms are still not getting rendered when the user clicks the button. I know there is nothing wrong with the template since the select forms are appended. They are however on browser default and have the property display:none.

What is the proper way to initialize the select forms on a button click?


Solution

  • Sure thing me from 10 minutes ago. All you have to do is initialize after you append you dumbdumb!

      $("#newColumnsButton").click(function() {
        for (let i = 1; i <= $("#numberOfColumns").val(); i++) {
          output.columnNumber.push(i);
        }
        $("#addColumnContainer").append(addColumnTemplate(output));
        $('select').material_select();
      });