循环使用HTML元素

时间:2017-09-20 09:42:23

标签: javascript jquery twitter-bootstrap

我有以下HTML / Bootstrap表单(动态生成):

<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>

这是JSFiddle: First time Downsize.

我需要遍历此表单并将dateKey和dateValue对存储到一个如下所示的数组中:

[
    {
        "dateKey":"revision",
        "dateValue":"2010-09-20"
    },
    {
         "dateKey":"publication",
         "dateValue":"2008-05-21"
    }
]

使用jQuery或纯JavaScript执行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:4)

$( 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