-1

I have a div which contains 7 checkboxes , i wrote this following code for accessing only the checked checkbox into the array icons

var icons = $("div").find("input[type=checkbox]").each(function () { 
if($(this).attr("checked") == "checked") return this; });

alert(icons.length);

but it always alert 7 .Can anybody tell me the problem?

1

5 Answers 5

3
var icons = $("div").find("input[type=checkbox]:checked");
Sign up to request clarification or add additional context in comments.

Comments

0

the easiest way is to assign a class to target inputs and use checked selector, see an example below:

var icons = $('.box:checked');

2 Comments

whats the need of class if we can do as @mgraph & ThulasiRam answered
@user1400722 $("div") will find every div on your page
0

Hiya demo http://jsfiddle.net/KzMqB/

You probably just need to check once using :checked and it will give you what you are looking for.

good read: http://api.jquery.com/checked-selector/

Hope this helps!

code

var icons = $("div").find("input[type=checkbox]:checked").each(function() {
           alert("ID of checked checkbox = " + $(this).attr("id"));
});

Comments

0

You can use $.map,

$(document).ready(function() {
    var checks = $.map($("div").find('input[type="checkbox"]:checked'),function(arr){
        return arr;
    })
    console.log(checks.length);
})

or your method,

$(document).ready(function() {
    var checks = $.each($("div").find('input[type="checkbox"]:checked'),function(){
        return this;
    })
    console.log(checks.length);
})

2 Comments

Well, checks will have the correct elements, but not because of $.each. The return value of the callback determines whether $.each should continue iterating over the elements or not. The return value is the first argument you pass to it. So essentially, your code is exactly the same as var checks = $("div").find('input[type="checkbox"]:checked');, just more convoluted. There is absolutely no need to use each. Have a look at the documentation: api.jquery.com/jQuery.each.
Yes. I have seen it now, there's no need to iterate. The question was on my mind and I just tried to fix the problem in it style. Thanks a lot ! I appreciate it.
0
var icons= $("div").find("input:checked").length;
alert(icons);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.