查找已选中复选框的顺序 [英] finding the order of which checkboxes have been checked
本文介绍了查找已选中复选框的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取已选中复选框的顺序.
I'm trying to get the order of which checkboxes have been checked.
<ul class="dropdown-content checkboxes">
<li><label><input type="checkbox" />Billy</label></li>
<li><label><input type="checkbox" />Jacob</label></li>
<li><label><input type="checkbox" />Bob</label></li>
<li><label><input type="checkbox" />Alexandren</label></li>
<li><label><input type="checkbox" />Erren</label></li>
<li><label><input type="checkbox" />Stewgart</label></li>
<li><label><input type="checkbox" />Jillian</label></li>
<li><label><input type="checkbox" />Other</label></li>
</ul>
我想出了这个,但是我无法获得选中复选框时的顺序.我只能获取仅选中哪些列表.
I came up with this but i'm unable to get the order of when the checkboxes were checked. I'm only able to get the list of which ones are checked only.
$(":checkbox").click(function() {
console.log($(":checked").length);
var i = 0;
checked = true;
$(':checkbox').each(function() {
if (this.checked == false) {
i++;
if (i === 8) {
checked = false;
}
}
});
});
如何获取检查顺序的数据?例如按此顺序选中了复选框1、6、3、2"
How would I get the data of what order they were checked? for instance "Checkboxes 1, 6, 3 ,2 were checked in this order"
推荐答案
您将跟踪选中了哪些复选框,例如在数组中
You'll have keep track of what checkboxes are checked, for instance in an array
var order = [];
$("[type=checkbox]").on('change', function() { // always use change event
var idx = order.indexOf(this);
if (idx !== -1) { // if already in array
order.splice(idx, 1); // make sure we remove it
}
if (this.checked) { // if checked
order.push(this); // add to end of array
}
// <------------------------------------For demonstration
$('#result').html(JSON.stringify($.map(order, function(elem) {
return $(elem).closest('label').text().trim();
})));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-content checkboxes">
<li><label><input type="checkbox" />Billy</label></li>
<li><label><input type="checkbox" />Jacob</label></li>
<li><label><input type="checkbox" />Bob</label></li>
<li><label><input type="checkbox" />Alexandren</label></li>
<li><label><input type="checkbox" />Erren</label></li>
<li><label><input type="checkbox" />Stewgart</label></li>
<li><label><input type="checkbox" />Jillian</label></li>
<li><label><input type="checkbox" />Other</label></li>
</ul>
<div id="result"></div>
要获取每个复选框(或更准确地说是父级LI)的索引,只需映射它们即可.
To get the index of each checkbox, or more accurately the parent LI, you could just map them
var map = $.map(order, function(elem) {
return $(elem).closest('li').index();
});
这篇关于查找已选中复选框的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文