JQUERY: get the id's of the checked and not checked checkBox

前端 未结 4 2047
你的背包
你的背包 2020-12-24 14:12

I have this not so many checkboxes:

 
相关标签:
4条回答
  • 2020-12-24 14:46

    I think I got a shorter version here:

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

    You can see it in action here: http://jsfiddle.net/XPMjK/3/

    0 讨论(0)
  • 2020-12-24 14:49
    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/

    0 讨论(0)
  • 2020-12-24 15:08

    I would do this something like this:

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

    After that you can use jQuery.map to get the ids of each collection.

    var checkedIds = checked.map(function() {
        return this.id;
    });
    
    var notCheckedIds = notChecked.map(function() {
        return this.id;
    });
    
    0 讨论(0)
  • 2020-12-24 15:08

    This can be done using .map, though in this case it is not really different from using .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.

    0 讨论(0)
提交回复
热议问题