首页 > 解决方案 > 如何通过javascript获取表格中的所有输入日期格式?

问题描述

我创建一个带有日期输入的 html 表:

<table id="myTable">
    <tr>
        <td><input name="start" type="date" value= ""/> ~ <input name="end" type="date" value=""/></td>
    </tr>
    <tr>
        <td><input name="start" type="date" value= ""/> ~ <input name="end" type="date" value=""/></td>
    </tr>
</table>

现在我想通过javascript获取所有输入值到字符串,如下所示:

2019-06-01~2019-06-02,2019-06-03~2019-06-04

我刚开始使用javascript,有人可以帮助我吗?很感谢!

标签: javascriptjqueryhtml

解决方案


您可以将输入作为字符串获取,如下所示:

function getDates() {
  var res = '';
  var rows = $('#myTable').find('tr');
  rows.each(function(index, el) {
    res += $(el).find('input[name=start]').val();
    res += '~';
    res += $(el).find('input[name=end]').val();
    if (index < rows.length - 1) {
      res += ', ';
    }
  });

  return res;
}

console.log(getDates());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
  <tr>
    <td><input name="start" type="date" value="2018-01-23" /> ~ <input name="end" type="date" value="2019-01-22" /></td>
  </tr>
  <tr>
    <td><input name="start" type="date" value="2018-01-23" /> ~ <input name="end" type="date" value="2019-01-28" /></td>
  </tr>
</table>


推荐阅读