【发布时间】:2020-03-30 03:37:47
【问题描述】:
情况很简单。我只想获取选择框的选定值。 我正在使用MaterializeCSS 和 JQuery。
Materialize 为其Select Form Item 提供了很好的文档。
在这里,我们可以了解到,选择框首先必须使用 formSelect() 函数进行初始化。 这就是我在我的 JavaScript 文件中所做的:
<div id="managementsite">
<h3 class="center">Management</h3>
<div class="toolbar">
<div class="input-field left">
<select>
<option value="" disabled selected>Choose Filter</option>
<option value="a">Define new filter</option>
<option value="1">Filter1</option>
<option value="2">Filter2</option>
</select>
</div><i class="material-icons left">check</i>
</div>
</div>
$(document).ready(function(){
$('#managementsite select').formSelect();
});
现在,选择框已初始化。
我现在想从中选择一个项目,单击一个按钮并从我选择的项目中获取值。 再次:价值!不是内部文本。
所以,Materialize 为我们提供了一种方法来做到这一点。 .getSelectedValues() 是要调用的函数。 但不幸的是,这只给了我一个长度为 1 的空字符串数组。
这就是我的工作:
$("#managementsite .toolbar").on("click", "i.material-icons", function(e){
var filter = $("#managementsite .toolbar .input-field ul li.selected");
console.log($('#managementsite .toolbar .input-field ul').formSelect("getSelectedValues"));
//Then do something with the value
});
我不引用选择字段的原因是,源选择字段将被隐藏并被类似
之类的东西覆盖<div class="select-wrapper">
<input class="select-dropdown dropdown-trigger" type="text" readonly="true" data-target="select-options-c51fc90b-2c60-e17d-9466-2e2cf7216a96">
<ul id="select-options-c51fc90b-2c60-e17d-9466-2e2cf7216a96" class="dropdown-content select-dropdown" tabindex="0">
<li class="disabled selected" id="select-options-c51fc90b-2c60-e17d-9466-2e2cf7216a960" tabindex="0"><span>Choose Filter</span></li>
<li id="select-options-c51fc90b-2c60-e17d-9466-2e2cf7216a961" tabindex="0"><span>Define new filter</span></li>
<li id="select-options-c51fc90b-2c60-e17d-9466-2e2cf7216a962" tabindex="0" class="selected"><span>Filter1</span></li>
<li id="select-options-c51fc90b-2c60-e17d-9466-2e2cf7216a963" tabindex="0"><span>Filter2</span></li>
</ul>
<svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg>
<select tabindex="-1">
<option value="" disabled="" selected="">Choose Filter</option>
<option value="a">Define new filter</option>
<option value="1">Sev4,5+PROD</option>
<option value="2">Only Java</option>
</select>
</div>
那么问题来了,如何正确调用 getSelectedValues() 方法。我在哪个对象上调用该方法?
正如您在上面看到的,当我选择一个选项时,<select>-<option> 不会改变。但是<ul>-<li> 可以,因为当我选择它时,<li> 中有class="selected"。
这意味着,我可以过滤选定的<li>,但我无法从<option> 标签中获取值。
想要这些值的原因是,我想区分“我选择一个过滤器”和“我想定义一个新过滤器”,即值“a”。选择值A时,我想显示一个模态,用户可以定义他的新过滤器。
选择其他值时,必须从数据库调用过滤器并应用。
希望你能理解我的问题。
请帮助我,我怎样才能从选择框/<ul>-List 中正确获取选定的值(!)?
你好,xola
【问题讨论】:
标签: jquery html jquery-selectors html-select materialize