input动态添加拼接json回显
动态添加删除input框,并且拼接成json,
以及后台json进行回显
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
var detail_div = 1;
function add_div() {
var e = document.getElementById("details");
var div = document.createElement("div");
div.className = "form-group";
div.id = "details" + detail_div;
div.innerHTML = e.innerHTML;
document.getElementById("form").appendChild(div);
detail_div++;
}
function del_div() {
if(detail_div >1){
var id = "details" + (detail_div - 1).toString();
var e = document.getElementById(id);
document.getElementById("form").removeChild(e);
detail_div--;
}
}
function tijiao(){
var params = [];
for(var i = 0;i<detail_div;i++){
var object = {};
var inputValue;
var inputValue2;
if(i==0){
inputValue = $("#details").find("#receivable").val();
inputValue2 = $("#details").find("#receivable1").val();
}else{
inputValue = $("#details"+i).find("#receivable").val();
inputValue2 = $("#details"+i).find("#receivable1").val();
}
object['goodsId'] = inputValue;
object['num'] = inputValue2;
params.push(object);
}
var json = JSON.stringify(params);
console.log(json);
}
$(function(){
var params = [];
var index=0;
var json = [{"goodsId":"10002","num":"1"},{"goodsId":"10003","num":"1"}];
$.each(json, function(idx, obj) {
var object = {};
object['goodsId'] = obj.goodsId;
object['num'] = obj.num;
params.push(object);
index ++;
});
for(var i=0;i<index;i++){
if(i ==0){
$("#details").find("#receivable").val(params[i].goodsId);
$("#details").find("#receivable1").val(params[i].num);
}else{
add_div();
$("#details"+i).find("#receivable").val(params[i].goodsId);
$("#details"+i).find("#receivable1").val(params[i].num);
}
}
})
</script>
<body>
<form id="form" role="form" method="post" class="formBuilder">
<div class="form-inline">
<label for="details" >操作</label>
<button type="button" id="add-btn" onclick="add_div()">+</button>
<button type="button" id="del-btn" onclick="del_div()">-</button>
</div>
<div id="details">
<div class="form-inline">
<label for="receivable" >选项</label>
产品名称:<input id="receivable" />
数量:<input id="receivable1" />
</div>
</div>
</form>
<button type="button" id="sub-btn" onclick="tijiao()">提交</button>
</body>
</html>