I have the following HTML/Bootstrap form (dynamically generated):
<div id="date_fields">
<div class="form-group removeclass0">
<div class="col-sm-6 nopadding">
<div class="form-group">
<input type="text" class="form-control dateKey" name="dateKey[]" value="revision">
</div>
</div>
<div class="col-sm-6 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control dateValue" name="dateValue[]" value="2010-09-20">
<div class="input-group-btn">
<button class="btn btn-danger" type="button" onclick="remove_date_fields(0);">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<div class="form-group removeclass1">
<div class="col-sm-6 nopadding">
<div class="form-group">
<input type="text" class="form-control dateKey" name="dateKey[]" value="publication">
</div>
</div>
<div class="col-sm-6 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control dateValue" name="dateValue[]" value="2008-05-21">
<div class="input-group-btn">
<button class="btn btn-danger" type="button" onclick="remove_date_fields(1);">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
Here is JSFiddle: https://jsfiddle.net/mleontenko/mmk9zo4L/
I need to loop through this form and store dateKey and dateValue pairs into an array that looks like this:
[
{
"dateKey":"revision",
"dateValue":"2010-09-20"
},
{
"dateKey":"publication",
"dateValue":"2008-05-21"
}
]
What is the best way to do this using jQuery or plain JavaScript?
$( document ).ready(function() {
var keys = [];
var values = [];
var res = [];
$.each($("#date_fields").find(".dateKey"), function(i, key) {
keys[i] = $(".dateKey:eq("+i+")").val();
});
$.each($("#date_fields").find(".dateValue"), function(i, value) {
values[i] = $(".dateValue:eq("+i+")").val();
});
$.each($("#date_fields").find(".dateValue"), function(i) {
res[i] = {"dateKey" : keys[i], "dateValue": values[i]};
});
$("#result").text(JSON.stringify(res));
});
JSFiddle: Working js fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.