我正在尝试将jQuery数组放入html输入中,但我无法弄清楚哪里出错了。

HTML:

<input type="hidden" id="datepicker" name="dates[]" />


jQuery:

<script>
$('#datepicker').datepick({
    dateFormat: 'yyyy-mm-dd',
    multiSelect: '100'
});
$(document).ready(function() {
    $("#butto").click(function() {
        var dates = $('#datepicker').datepick('getDate');
        console.log(dates);

        $('#datepicker').val(dates);
    });
});
</script>


PHP:

$dates= $this->input->post('dates');

foreach($dates as $datee) {
    print_r($datee);
}

最佳答案

您无法直接获取dates数组,因为多重选择日期默认是通过逗号(,)传递的。因此,您需要先进行小技巧,然后再提交表单数据。贝娄是实现结果的自定义代码。

jQuery代码

<script>
    $('#datepicker').datepick({

      dateFormat: 'yyyy-mm-dd',
      multiSelect: '100',

      //convert the selected date into array and assign the value to your hidden filed when the date picker will close by any format

      onClose: function(dates) {
         var selectedDate = [];
         for (var i = 0; i < dates.length; i++) {
             selectedDate.push($.datepick.formatDate(dates[i]));
         }
         $('#datepicker').val(JSON.stringify(selectedDate));
      },

   });
</script>


PHP代码

在服务器端捕获隐藏的字段值,并使用json_decode函数对其进行解码以获取日期数组。

$dates= json_decode($this->input->post('dates'));

foreach($dates as $datee) {
   print_r($datee);
}


希望它能按预期工作。

09-25 17:20
查看更多