使用ajax使提交后选中的复选框可见


Make Checkbox that checked after submit to be visible using ajax

我有一张表格,记录员工的出勤情况。提交后,我需要选中所选员工的复选框。表单是通过ajax提交的。下面是插入全体员工出席情况的代码。

     var _data = new FormData($('#formaction')[0]);
     $.ajax({
        type: 'POST',
        dataType:"json",
         processData: false,
        contentType: false,
        url: '<?php echo base_url();?>SchoolAdmin/insertAttendance',
        data: _data,
        success: function (result) {
          console.log(result);
          staffattendance();

        }
     });

function staffattendance()
{
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)?       (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
//var currentDate = fullDate.getDate() + "/" + twoDigitMonth + "/" +   fullDate.getFullYear();   
var currentDate = fullDate.getFullYear()+"-"+ twoDigitMonth +"-"+fullDate.getDate();
   $.ajax({
            type: 'POST',
            dataType:"json",
            url: '<?php echo base_url();?>SchoolAdmin/staffattendance',
            data: {currentDate:currentDate},
            success: function (result) {
                $.each(result, function (i, item) {
              console.log(result[i].staff_id);
               $('.teachers').prop('checked', true);
              });
            }
});

}

在这里,我调用了一个函数staffattendance(),以获取当天在场的员工的员工id。因此,我需要将通过该功能收到的员工id与复选框字段相匹配,并且应该处于选中模式。下面是动态生成带有人员名称的复选框的代码。

     <?php foreach($teacher as $row)
     {?>
            <tr><td>
     <?php echo $row->name;?>
               </td>
               <td>
      <input type="checkbox" name="teachers[]" class="teachers" value="<?php echo $row->staff_id;?>" >
      <input type="hidden" name="teachers1[]" class="teachers1" value="<?php echo $row->staff_id;?>">
              </td>
              </tr>
    <?php }?>

因此,我需要保留从staffattendance()函数获得的staff_id的复选框。

如何做到这一点。

Rose,问题有点不清楚,因为您没有指定何时生成带有名称和复选框的表,以及此表是否会受到ajax成功的影响。。

你可以试试:

$.each(result, function (i, item) {
   console.log(result[i].staff_id);
   $('.teachers[value="'+result[i].staff_id+'"]').prop('checked', true);
});