首页 > 解决方案 > 根据所选日期填写星期几

问题描述

我有一个表格,其中包含一个数据列和一个星期几在选择日期时,我希望该列根据所选数据填充日期名称

我正在尝试这样:

$('#add').click(function(){
   var html = '<tr>';
    html += '<td contenteditable ><input type="date" class="data1" id="data1"/></td>';
    html += '<td><input type="text" class="data2" id="data2"/></td>';
    html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-send"></span></button></td>';
   html += '</tr>';
   $('#user_data tbody').prepend(html); //<--- right here

});

$(document).ready(function(){
    var semana = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"];
    $(".data1").on(function(){
        var data = this.value;
        var arr = data.split("-").reverse();
        var teste = new Date(arr[0], arr[1] - 1, arr[2]);
        var dia = teste.getDay();
        $(".data2").val();
    });
});

但在设置日期时不显示警报。日期在以下表格中input type = date:04-07-2019

HTML:

<div align="right">
     <button type="button" name="add" id="add" class="btn btn-info"><span class="glyphicon glyphicon-plus"></span></button>
    </div>
    <br />
    <div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
    <thead>
     <tr>
      <th>Data</th>
      <th>Dia da Semana</th>
      <th></th>
     </tr>
    </thead>
    <tbody>
    </tbody>
</table>

标签: javascriptjqueryhtml

解决方案


您应该阅读上面的 ADyson 注释,并因此对您的代码进行一些更改。一些简单的例子是:

var daysInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

$('#add').click(function() {
    var html = '<tr>';
    html += '    <td><input type="date" class="input-date" /></td>';
    html += '    <td><input type="text" class="input-day" /></td>';
    html += '    <td><button type="button" class="button-insert">Insert</button></td>';
    html += '</tr>';
    $('#user_data tbody').prepend(html);
});

$("body").on('change', '.input-date', function(e) {
    var thisDate = $(this);
    var data = thisDate.val();
    var teste = new Date(data);
    var dia = teste.getDay();
    var closestRow = thisDate.closest('tr');
    closestRow.find('.input-day').val(daysInWeek[dia]);
});

$("body").on('click', '.button-insert', function(e) {
    var thisButton = $(this);
    var closestRow = thisButton.closest('tr');
    /* Do whatever you want */
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <button type="button" id="add">Add</button>
</div>
<table id="user_data">
    <thead>
        <tr>
            <th>Data</th>
            <th>Dia da Semana</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

所以,没有重复的 ID,第二个是jQuery 事件委托......

同样在JS Fiddle上。


推荐阅读