我正在尝试从Jquery的html中为select元素添加一个选项。 我使用表单提交要添加到select元素的类别的名称。新类别选项在检查代码时显示,但是它没有显示在文档中。
$(document).ready(function () {
// initialization
$('select').formSelect();
$('#myForm').submit(function (e) {
let category = $('#in').val();
$('#selection').append(`<option value="${category}">${category}</option>`);
e.preventDefault();
})
});
&#13;
<!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Lab</title>
</head>
<body>
<div class="container">
<form id="myForm">
<div class="input-field">
<label for="in">Enter category</label>
<input type="text" id="in">
</div>
<select id="selection">
<option value="" selected disabled>Category</option>
<option value="1">1</option>
</select>
<button class="btn" type="submit">Submit</button>
</form>
</div>
</body>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script src="app.js"></script>
</html>
&#13;
答案 0 :(得分:1)
问题是因为您正在使用一个插件来重建HTML中的select
元素,允许您根据需要设置样式。这意味着未检测到初始化后附加到select
的任何新选项。
要解决此问题,请在表单formSelect()
事件处理程序中再次调用submit
:
$(document).ready(function() {
$('select').formSelect();
$('#myForm').submit(function(e) {
e.preventDefault();
let category = $('#in').val();
$('#selection').append(`<option value="${category}">${category}</option>`);
$('select').formSelect();
})
});
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<div class="container">
<form id="myForm">
<div class="input-field">
<label for="in">Enter category</label>
<input type="text" id="in">
</div>
<select id="selection">
<option value="" selected disabled>Category</option>
<option value="1">1</option>
</select>
<button class="btn" type="submit">Submit</button>
</form>
</div>
然而,应该注意的是,用户体验相当奇怪。你必须在字段中输入,然后提交表单(似乎什么都不做),然后提交按钮上方的选项改变了它的选项。这不是很直观。