Javascript 如何在materialize css框架中动态修改<select>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29132125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically modify <select> in materialize css framework
提问by user1432882
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:
我刚开始使用 materialize css 框架。现在,materialize 将任何选择标记转换为 ul 和 li 元素的集合。之前,使用 JQuery,我能够做到这一点:
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:
我的 html 只是一个示例选择标签:
Before, this was working. Now it fails. What would be an alternative for repopulating this dropdown dynamically using javascript?
以前,这是有效的。现在它失败了。使用 javascript 动态重新填充此下拉列表的替代方法是什么?
回答by KyleMit
According to the Docs on Materialize Forms:
In addition, you will need a separate call for any dynamically generatedselect elements your page generates
此外,您将需要对页面生成的任何动态生成的选择元素进行单独调用
So the best way is to just re-bind the generated select with an additional call to .material_select().
所以最好的方法是重新绑定生成的 select 并额外调用.material_select().
For re-usability, you can set up a listener when the elements have changedand then trigger that listener whenever you update the original select
为了可重用性,您可以在元素更改时设置一个侦听器,然后在更新原始选择时触发该侦听器
// 1) setup listener for custom event to re-initialize on change
$('select').on('contentChanged', function() {
$(this).material_select();
});
// 2a) Whenever you do this --> add new option
$selectDropdown.append($("<option></option>"));
// 2b) Manually do this --> trigger custom event
$selectDropdown.trigger('contentChanged');
This has the benefit of only needing to update the particular select element that has changed.
这样做的好处是只需更新已更改的特定选择元素。
Demo in jsFiddle& Stack Snippets:
jsFiddle& Stack Snippets 中的演示:
$(function() {
// initialize
$('.materialSelect').material_select();
// setup listener for custom event to re-initialize on change
$('.materialSelect').on('contentChanged', function() {
$(this).material_select();
});
// update function for demo purposes
$("#myButton").click(function() {
// add new value
var newValue = getNewDoggo();
var $newOpt = $("<option>").attr("value",newValue).text(newValue)
$("#myDropdown").append($newOpt);
// fire custom event anytime you've updated select
$("#myDropdown").trigger('contentChanged');
});
});
function getNewDoggo() {
var adjs = ['Floofy','Big','Cute','Cuddly','Lazy'];
var nouns = ['Doggo','Floofer','Pupper','Fluffer', 'Nugget'];
var newOptValue = adjs[Math.floor(Math.random() * adjs.length)] + " " +
nouns[Math.floor(Math.random() * nouns.length)];
return newOptValue;
}
body { padding: 25px}
<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>
<button class="waves-effect waves-light btn" id="myButton">
Add New Option to Dropdown
</button>
<select id="myDropdown" class="materialSelect">
<option value="Happy Floof">Happy Floof</option>
<option value="Derpy Biscuit">Derpy Biscuit</option>
</select>
回答by Nimsrules
You can reinitialize the select element after your data is bound successfully. Like so,
您可以在数据绑定成功后重新初始化 select 元素。像这样,
$('select').material_select();
Similar to this:
与此类似:
var next_id = $(".mtr-select");
$.each(json, function(key, value) {
$(next_id).append($("<option></option>").attr("value", value.id).text(value.name));
});
$(next_id).material_select();
It binds its option values to new ul>lielement by creating the dom object on load.
它ul>li通过在加载时创建 dom 对象将其选项值绑定到新元素。
回答by Davide Caruso
This is a valid solution for MaterializeCss v0.96.1. In version 0.97.0 it doesn't work: seems that there is a bug that appends a caret in the HTML.
这是 MaterializeCss v0.96.1 的有效解决方案。在 0.97.0 版本中它不起作用:似乎有一个错误在 HTML 中附加了一个插入符号。
Here the code for v0.97.0:
这里是 v0.97.0 的代码:
$(document).ready(function() {
// Initialize
$('select').material_select();
$("button").click(function() {
// Clear the content
$("select").empty().html(' ');
// And add a new value
var value = "New value";
$("select").append(
$("<option></option>").attr("value",value).text(value)
);
// Update the content clearing the caret
$("select").material_select('update');
$("select").closest('.input-field').children('span.caret').remove();
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/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.97.0/js/materialize.min.js"></script>
<button class="btn-large blue waves-effect waves-light">Change</button>
<div class="input-field">
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</div>
回答by Huntr
This works for Materialize 1.0.0-rc.1:
这适用于Materialise 1.0.0-rc.1:
the situation: I have two fields; first is to select a category
情况:我有两个字段;首先是选择一个类别
<select name="category" id="category">
<option value="0">Choisissez une Catégorie</option>
<option value="1">Audios</option>
<option value="2">Vidéos</option>
<option value="3">Applications</option>
<option value="4">Jeux Vidéos</option>
</select>
after category is selected, the second select id="subcategory" is populated with good subcats according to the parent category:
选择类别后,第二个选择 id="subcategory" 根据父类别填充好子猫:
<select name="subcategory" id="subcategory" disabled="disabled">
<option value="0">Choisissez une sous-catégorie</option>
</select>
var subCategoriesNames = ['Tout', ['Tout', 'Musiques', 'Concerts', 'Comédies'], ['Tout', 'Films', 'Séries TV', 'Emissions TV', 'Documentaires', 'Animations', 'Animations Séries', 'Concerts', 'Sports'], ['Tout', 'Livres', 'Magazines', 'Presses', 'Mangas', 'BD'], ['Tout', 'Formations', 'Android', 'Windows', 'Linux', 'Web', 'Emulateurs'], ['Tout', 'Android', 'Windows', 'Consoles', 'Linux']],
subCategoriesIds = ['1', ['2', '3', '4', '5'], ['6', '7', '8', '9', '10', '11', '12', '13', '14'], ['15', '16', '17', '18', '19', '20'], ['21', '22', '23', '24', '25', '26', '27'], ['28', '29', '30', '31', '32']],
idx = 0,
subsName;
$(document).ready(function(){
$('#category').on('change', function(){
idx = this.selectedIndex;
if(idx > 0){
$('select#subcategory').attr('disabled', false);
for(subsName in subCategoriesNames[idx]) $('select#subcategory').append('<option value="'+subCategoriesIds[idx][subsName]+'">'+subCategoriesNames[idx][subsName]+'</option>');
}else{
$('select#subcategory').attr('disabled', true);
}
var subcatSelectElem = document.querySelectorAll('#subcategory');
var subcatSelectInstance = M.FormSelect.init(subcatSelectElem, {});
})
});
回答by Peter Braganza
Hi as you are using materialize framework, using simple generates other container elements for the same. hence using jquery select tag wont do the required task you need
嗨,因为您使用的是 materialize 框架,所以使用 simple 生成相同的其他容器元素。因此使用 jquery select 标签不会做你需要的任务
I found this which works fine for me
我发现这对我来说很好用
<select class="className"></select>
**$('.className').formSelect().append($('<option>'+data[i]+'</option>'))**
hope this works for you too
希望这对你也有用
回答by jsea
In Materialize v1.0.0, all you have to do is call $('.yourSelect').formSelect();after removing or adding optionelements from your selectelement.
在 Materialize v1.0.0 中,您只需$('.yourSelect').formSelect();在从option元素中删除或添加元素后调用即可select。
回答by rahul shukla
$('select').material_select(); // for initializing the material select box
$("select").closest('.input-field').children('.select-wrapper').children("span").html("");

