How to dynamically modify <select> in materi

2019-01-13 13:54发布

I just started using the materialize css framework. Now, materialize converts any select tag into a collection of ul and li elements. Before, using JQuery, I was able to do this:

var $selectDropdown = $("#dropdownid");
$selectDropdown.empty();
$selectDropdown.html(' ');
var value = "some value";
$selectDropdown .append($("<option></option>").attr("value",value).text(value));

My html is just a sample select tag:

Before, this was working. Now it fails. What would be an alternative for repopulating this dropdown dynamically using javascript?

7条回答
可以哭但决不认输i
2楼-- · 2019-01-13 14:25
$(document).ready(function() {

  // initialize
  $('select').material_select();


  $("#myButton").click(function() {

    // clear contents
    var $selectDropdown = 
      $("#dropdownid")
        .empty()
        .html(' ');

    // add new value
    var value = "some value";
    $selectDropdown.append(
      $("<option></option>")
        .attr("value",value)
        .text(value)
    );

    // trigger event
    $selectDropdown.trigger('contentChanged');
  });


  $('select').on('contentChanged', function() {
    // re-initialize (update)
    $(this).material_select();
  });

});



     <link  href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1 /css/materialize.min.css" rel="stylesheet">
     <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3 /jquery.min.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/js/materialize.min.js"></script>

  <a class="waves-effect waves-light btn" id="myButton">
  Change Dropdown
  </a>

<select id="dropdownid" >
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select>
查看更多
登录 后发表回答