JQUERY:获取已检查且未选中的复选框的ID

时间:2011-08-01 16:10:16

标签: jquery arrays checkbox

我没有这么多复选框:

<input type="checkbox" id="mango" value="mango" /> <label>MANGO</label><br>
<input type="checkbox" id="santol" value="santol" /> <label>SANTOL</label><br>
<input type="checkbox" id="guava" value="guava" /> <label>GUAVA</label><br>
<input type="checkbox" id="lomboy" value="lomboy" /> <label>LOMBOY</label><br>
<input type="checkbox" id="apple" value="apple" /> <label>APPLE</label><br>
<input type="checkbox" id="orange" value="orange" /> <label>ORANGE</label><br>
 ...................<>

现在,我正在尝试做的是检查所有ID的复选框,而不检查并放入数组。像这样:

"fruitsGranted":["apple","lomboy","orange"]; //check is true
"fruitsDenied":["mango","santol","guava"];  //check false

可以请有人告诉我该怎么做。感谢。

4 个答案:

答案 0 :(得分:42)

var someObj={};
someObj.fruitsGranted=[];
someObj.fruitsDenied=[];

$("input:checkbox").each(function(){
    var $this = $(this);

    if($this.is(":checked")){
        someObj.fruitsGranted.push($this.attr("id"));
    }else{
        someObj.fruitsDenied.push($this.attr("id"));
    }
});

http://jsfiddle.net/UqrYJ/

答案 1 :(得分:25)

我想我的版本更短:

var idSelector = function() { return this.id; };
var fruitsGranted = $(":checkbox:checked").map(idSelector).get();
var fruitsDenied = $(":checkbox:not(:checked)").map(idSelector).get();

您可以在此处看到它:http://jsfiddle.net/XPMjK/3/

答案 2 :(得分:5)

我会这样做:

var all, checked, notChecked;
all = $("input:checkbox");
checked = all.filter(":checked");
notChecked = all.not(":checked)");

之后,您可以使用jQuery.map获取每个集合的ID。

var checkedIds = checked.map(function() {
    return this.id;
});

var notCheckedIds = notChecked.map(function() {
    return this.id;
});

答案 3 :(得分:2)

这可以使用.map完成,但在这种情况下与使用.each并没有什么不同:

$(":checkbox").change(function() {
    var notChecked = [], checked = [];
    $(":checkbox").map(function() {
        this.checked ? checked.push(this.id) : notChecked.push(this.id);
    });
    alert("checked: " + checked);
    alert("not checked: " + notChecked);
});

You can test it here.