我正在尝试通过单击一个加号按钮添加多个字段。然后我有四个特定文本字段的数组:company
,from
,to
和year
。如果我单击按钮,我将获得四个字段。我想输入值并将值保存在四个数组中。当我再次点击该按钮时,应该发生同样的事情。
数组仅保存每个字段的第一个值,另一个值为null。如何保存数组中的所有值?
var company = [];
var from = [];
var to = [];
var year = [];
var scntDiv = $('#addmorefieldexp');
var i = $('#addmorefieldexp p').size() + 1;
/* $('#pexp').live('click', function() */
$("#pexp").click(function(){
$( ' <br><br>'
+'<label for="inputPassword3" class="col-sm-2 control-label">Company Name</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_company[]" value="" id="company">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">From</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_from[]" value="" id="from">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">To</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_to[]"value="" id="to">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">Year</label>'
+'<div class="col-sm-1">'
+'<input type="text" class="form-control" name="field_year[]"value="" id="year">'
+'</div>').appendTo(scntDiv);
var add_company = $("input[name$='field_company[]']").val();
company.push(add_company);
var add_from = $("input[name$='field_from[]']").val();
from.push(add_from);
var add_to = $("input[name$='field_to[]']").val();
to.push(add_to);
var add_year = $("input[name$='field_year[]']").val();
year.push(add_year);
console.log(company, from, to, year);
return false;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="form-group" id="experience">
<label class="col-sm-2 control-label">Employment Experience</label>
<div class="col-sm-4" id="checkbox" value="">
<input type="radio" name="exp" class="expp" value="Yes">Yes
<input type="radio" name="exp" class="expp" value="No">No
<button class="btn btn-lg btn-sm btn-primary btn-circle" id="pexp"><i class="fa fa-plus"></i>
</button>
</div>
</div>
<div class="form-group text-center" id="addmorefieldexp">
<p>
</p>
</div>
&#13;
答案 0 :(得分:0)
你只需编写一个for循环来遍历所有输入字段,如下所示:
Promise
答案 1 :(得分:0)
我完成了!!!我必须添加它以节省数组的值。
var inps = document.getElementsByName('field_company[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
company.push(inp.value);