$('#subjects input[type=checkbox]').on('click',function(){
alert($(this).prop('checked'));
});
或更改事件:以防有人使用键盘
$('#subjects input[type=checkbox]').on('change',function(){
alert($(this).prop('checked'));
});
简单的小提琴示例:http: //jsfiddle.net/Dr8k8/
要获取数组示例,请使用输入的索引
alert($(this).prop('checked') +'is'+ $(this).parent().find('input[type=checkbox]').index(this)+ responseArray[$(this).parent().find('input[type=checkbox]').index(this) ]);
简化示例:http: //jsfiddle.net/Dr8k8/1/
编辑:仅举个例子,您可以将结果放在所有选中框的数组中,然后用它做一些事情:
$('#subjects>input[type=checkbox]').on('change', function() {
var checklist = [];
$(this).parent().find('input[type=checkbox]').each(function() {
$(this).css('background-color', "lime");
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist[myindex] = responseArray[myindex];
}
});
$('#currentlyChecked').text(checklist);
});
编辑2:
我考虑了一下,您可以通过使用 .data() 并根据事件查询或存储它来改进它(我的按钮由其 id 为“whatschecked”调用)
var responseArray = ['math', 'science', 'technology', 'engineering'];// just for an example
var myList = '#subjects>input[type=checkbox]';//to reuse
for (var x = 0; x < responseArray.length; x++) {
// here we insert it all so we do not hit the DOM so many times
var iam = "<br />" + responseArray[x] + "<input type='checkbox' />";
$("#subjects").append(iam);
$(myList).last().data('subject', responseArray[x]);// add the data
}
var checklist = [];// holds most recent list set by change event
$(myList).on('change', function() {
checklist = [];
$(myList).each(function() {
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist.push($(this).data('subject'));
alert('This one is checked:' + $(this).data('subject'));
}
});
});
// query the list we stored, but could query the checked list data() as well, see the .each() in the event handler for that example
$("#whatschecked").click(function() {
var numberChecked = checklist.length;
var x = 0;
for (x = 0; x < numberChecked; x++) {
alert("Number " + x + " is " + checklist[x] + " of " + numberChecked);
}
});
最后一个的实例:http: //jsfiddle.net/Dr8k8/5/