首页 > 解决方案 > 如何使用带有日期选择器的 jQuery 使文本出现在另一个文本框中?

问题描述

我有一个调用日期选择器并允许用户选择日期的输入文本框。我需要日期在另一个文本框中显示为一天。问题是只有在您选择日期然后再次单击日期输入框后才会填充日期文本框。日期文本框似乎不会从日期选择器中的 onSelect 自动填充。我需要它在用户选择日期后立即出现。

我已经尝试使用带有焦点事件的 .on 方法和 datepicker 中的 onSelect 属性,它应该运行我的函数以立即显示这一天....使用的原因是.on包含输入文本框的行是从动态加载的初始页面加载后的代码隐藏。

$('body').on('focus', ".datepickerInput", function () {
    $(this).datepicker({
        controlType: "select",
        onSelect: showDay($(this).attr("id"))
    });
});
function showDay(id) {
    var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var dateVal = "";
    var Day = $("#" + id).closest('tr').find('td:eq(5) input').attr('id')
    dateVal = $("#" + id).val();
    var x = new Date(dateVal);
    dayOfWeek = weekday[x.getDay()];
    $("#" + Day).val(dayOfWeek);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.js"></script>
<table>
         <thead>
          <tr>
           <th>infoW</th>
           <th>infoX</th>
           <th>infoY</th>
           <th>infoZ</th>
          </tr>
         <thead>
         <tbody>
          <tr>
           <td>
           <input type="text asp-for="Shift0">
           </td>
           <td>
           <input type="text" asp-for="Date0" class="datepickerInput"/>
           </td>
           <td>
           <input type="text" asp-for="Time0" class="timepickerInput" />
           </td>
           <td>
           <input type="text" asp-for="Day0" />
           </td>
          </tr>
          <td>
           <input type="text asp-for="Shift1">
           </td>
           <td>
           <input type="text" asp-for="Date1" class="datepickerInput"/>
           </td>
           <td>
           <input type="text" asp-for="Time1" class="timepickerInput" />
           </td>
           <td>
           <input type="text" asp-for="Day1" />
           </td>
          <tr>
           @*..More of the same tds with different ids.*@
          </tr>
         </tbody>
        </table>

日期文本框应根据选择日期时从日期文本框中选择的日期填充实际日期。

标签: jqueryhtml

解决方案


您可以简单地使用altFieldaltFormat选项来自动填充其他输入。

$('#picker').datepicker({
  altField: '#output',
  altFormat: 'DD'
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<input type="text" id="picker">
<input type="text" id="output">


推荐阅读