嗯。。标题可能看起来很模糊,但这个问题对我来说有点新。
我有一个复选框,它使用循环(在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
元素,其中value
与shift_id
匹配。为此,可以使用属性选择器。试试这个:
$.each(shifts, function (index, shift) {
$('.shiftt_class[value="' + shift.shift_id + '"]').prop("checked", true);
});
示例fiddle
还要注意,对返回数据的length
检查是多余的,因为循环无论如何都不会在空数组上执行。