使用jQuery检查复选框值时出错


Error in checking checkbox value using jQuery

嗯。。标题可能看起来很模糊,但这个问题对我来说有点新。

我有一个复选框,它使用循环(在php中)设置了n次。

<input class="shiftt_class" type="checkbox" name="multiSelect[]" value="">

它是这样设置的。

<?php foreach($depts['shifts'] as $shfts){?>
   <span>
     <input class="shiftt_class" type="checkbox" name="multiSelect[]" value="<?php echo $shfts['shift_id'];?>">
     <select name="nottime<?php echo $shfts['shift_id']; ?>" class="notification_time_class">
        <option value="">Set Time</option>                     
        <option value="11:00" >11:00</option>                               
        <option value="12:00" >12:00</option>                     
        <option value="13:00">13:00</option>                           
      </select>                      
  </span>
<?php }?>

单击一个按钮,我就尝试设置基于使用jQuery获得的JSON响应所选的复选框。

我的JSON响应:

[{"shift_id":"2"},{"shift_id":"3"}]

jQuery代码:

如果shifts是我的JSON响应,那么

           if(shifts.length>0)
           {
             $.each(shifts,function(index,shift) 
             {
                    if($(".shiftt_class").val()==shift.shift_id)
                    {
                        alert('ddd');
                        $(".shiftt_class").prop("checked", true);                           
                    }
              });//end of each function
            }

我启动了警报,但复选框未设置。我也要尝试同样的方法来设置选择框。我哪里错了?

更新:我的jQuery函数

        $.ajax({
             url: post_url,
             data:{staff_id : staff_id,csrf_test_name : csrf_token},
             type: "POST",
             dataType: 'json',
             beforeSend: function ( xhr ) {
             //Add your image loader here
             $('#select_loader').show(); // Ajax Loader Show
             },
             success: function(shifts) 
            { 
                 $('#select_loader').hide();
                $.each(shifts, function (index, shift) {$('.shiftt_class[value="' + shift.shift_id + '"]').prop("checked", true);
}); 
            }
        });//end of ajax

问题是因为each()块中的.shiftt_class选择器正在检索所有元素。在那个问题上调用val()是令人困惑的。您应该在迭代中查找.shiftt_class元素,其中valueshift_id匹配。为此,可以使用属性选择器。试试这个:

$.each(shifts, function (index, shift) {
    $('.shiftt_class[value="' + shift.shift_id + '"]').prop("checked", true);
});

示例fiddle

还要注意,对返回数据的length检查是多余的,因为循环无论如何都不会在空数组上执行。