How to dynamically add input fields in layui?
In Layui, you can dynamically add input fields using the following code.
<div id="container">
<button class="layui-btn layui-btn-primary" id="addInput">添加输入框</button>
</div>
<script>
layui.use(['element', 'form'], function(){
var element = layui.element;
var form = layui.form;
// 添加输入框
$("#addInput").on("click", function() {
var inputHtml = '<div class="layui-form-item"><input type="text" name="input[]" placeholder="请输入内容" autocomplete="off" class="layui-input"></div>';
$("#container").append(inputHtml);
// 重新渲染表单元素
form.render();
});
});
</script>
The above code first places a button in a div container, and when the button is clicked, it dynamically adds an input box to the container.
In JavaScript code, first load the element and form modules using layui.use method, and then in the click event handler function, use jQuery’s append method to add HTML code of an input box to the container.
Finally, call the form.render() method to re-render the form elements so that the newly added input box can display the correct style.