我不太确定解决这个问题的最佳方法,但我已经奠定了框架。
基本上,我想添加功能,以便当单击 #moreItems_add 按钮并调用 moreItems 函数时,我只想在其下方添加一个新的输入字段,依此类推。不过,我想将其限制为 10 个字段,因此我在函数中显示了这一点。
唯一的技巧是,我将通过 ajax 提交所有字段以保存到数据库,因此我需要尝试跟踪每个字段的 ID。
在这里继续执行 javascript 的最佳方式是什么,以便我可以在按下按钮时附加一个输入字段并跟踪每个字段的 ID?
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
<!-- modal JS -->
<script type="text/javascript">
function moreItems(){
var MaxItems = 10;
//If less than 10, add another input field
}
</script>
最佳答案
您可以使用 jQuery .insertBefore() 方法在“更多项目”按钮之前插入元素。下面是代表这一点的代码:
var maxItems = 1;
function moreItems() {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
maxItems++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button type="button" id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
关于javascript - 如果单击按钮,则将输入添加到表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52283418/