将数组中的值放入以逗号分隔的输入值

时间:2017-03-29 13:28:15

标签: jquery arrays join input

我有多个日期数组,我需要将它们放在输入类型的隐藏字段值中。

["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]
["26/2/2017"]

我想这样做:

<input type="hidden" value="5/3/2017, 12/3/2017, 19/3/2017, 26/3/2017, 26/2/2017">

我尝试使用merge,join()但我设法只获得一个输入值,我认为它是最后一个值。有什么想法吗?

以下是我尝试执行此操作的代码的一部分:

        var dayAll = sundayData['date'];
        var monthAll = sundayData['month'];
        var yearAll = sundayData['year'];

        var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;

        var sundayDate = [];

        sundayDate.push(sundayDatesAll);

        $('input').val(sundayDate);

我从sundayDate获取数组

2 个答案:

答案 0 :(得分:0)

试试这个:

注意:根据您的要求替换部分代码

&#13;
&#13;
var dateArray = [];

var dayAll = "5,12,19,26,26";
var monthAll = "3,3,3,3,2";
var yearAll = "2017,2017,2017,2017,2017";

var dayArray = dayAll.split(",");
var monthArray = monthAll.split(",");
var yearArray = yearAll.split(",");

for (var i = 0; i < dayArray.length; i++) {

    var sundayDate = dayArray[i] + '/' + monthArray[i] + '/' + yearArray[i];
    dateArray.push(sundayDate);
}

var dateString = dateArray.join();
console.log(dateString);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

请检查是否需要为我们提供完整的代码,以便知道发生了什么。 但尝试同样的,我认为这个问题解决了。

sundayDatesAll[0] = ["5/3/2017"]; 
sundayDatesAll[1] = ["12/3/2017"]; 
sundayDatesAll[2] = ["19/3/2017"]; 
sundayDatesAll[3] = ["26/3/2017"]; 

sundayDate.push(sundayDatesAll);

var manvar = sundayDate.join();

alert(manvar);

https://jsfiddle.net/manish1226/8py4o6uc/3/