我有一系列复选框,我使用foreach循环(php)填充。代码如下所示:
<input type="checkbox" name="artist_group[]" id="{{$fb_data['fbid']}}" class="input-hidden" data-name="{{$fb_data['name']}}" value="{{$fb_data['fbid']}}" style="display:none;" />
<label for="{{$fb_data['fbid']}}">
<img src="https://graph.facebook.com/{{$fb_data['fbid']}}/picture?width=200&height=200" width="140" height="140" alt="{{$fb_data['name']}}"/>
<article class="artistName">{{$fb_data['name']}}</article>
</label>
我想要检查是否使用javascript检查了任何复选框。但是,我无法使用"getElementById"
执行此操作,因为我希望每个复选框都具有唯一的ID(因此我可以提取数据)。我将复选框组的名称作为数组,因此我可以将所有选中的框发送到我的后端。我可以这样做吗?:
if (document.getElementByName('artist_group').checked) {
alert("checked");
}
感谢您的帮助。
答案 0 :(得分:2)
您已遍历复选框并测试是否已选中其中任何一个。请注意,方法名称为 getElementsByName
(带有s的元素):
var boxes = document.getElementsByName('artist_group[]');
var checked = false;
for (var i = 0, l = boxes.length; i < l; i++) {
if (boxes[i].checked) {
checked = true;
break;
}
}
如果您不反对较新的JavaScript方法,也可以使用Array#some
:
var checked = Array.prototype.some.call(boxes, function(input) {
return input.checked;
});
使用jQuery,它甚至更简单:
var checked = $('input[name="artist_group[]"]:checked').length > 0;
答案 1 :(得分:0)
既然您在问题中标记了jQuery,也可以使用jQuery的$ .each。
只需按类选择元素而不是id。
$('.input-hidden').each(function() {
//this will iterate through all checkboxes
if ($(this).is(':checked')) {//Per @Felix's comment, this.checked is a more native way of doing it, I personally just prefer to use $(this) when I'm in jQuery context, to be consistent. Using this.checked is quicker though.
//this will apply just to the checked checkboxes
}
});
您也可以通过以下方式获取所选复选框:
$('input:checked').each(function() {
//this will only apply to selected checkboxes
});
希望这有帮助!
答案 2 :(得分:0)
正如您还在使用jQuery标记进行提问:如果您正在使用jQuery(不要仅为此任务添加它,那就太过分了!):
if ( ! $('input[name="artist_group"]').is(':not(:checked)') ) {
// all are selected
}