views:

223

answers:

2

I'm expanding further on this question.

I currently have an asp.net hyperlink for Select All (NumberOfCheckBoxes) which works, but what I'm looking to do is add another link, possibly just a standard HTML hyperlink for Uncheck Selected (NumberOfCheckedBoxes) and update the value of NumberOfCheckedBoxes as checkboxes are ticked without reloading the page.

I have javascript already for unchecking them, but not counting them and printing it to screen.

I'm not sure if jQuery is the way to go with this or just standard Javascript.

Thanks in advance for any help.

+5  A: 

With jQuery you can:

$("input:checkbox:checked").length;
Zed
Or $("input:checkbox:checked").length; (P.s. you'll need the semi-colon after size()
James Wiseman
can I do document.write($("input:checkbox:checked").length);?
Liam
If you have the jQuery library included in page, yes
James Wiseman
@James Thanks for the comments. According to jQuery docs, "[size()] returns the same number as the 'length' property of the jQuery object. However, it is slightly slower, so length should be used instead.", so length is even preferred over size().
Zed
@both of you - is there a way of updating the value output by $("input:checkbox:checked").length; without reloading the page at all? I've added jQuery to my page and just made my link look like <a href="#" onclick="uncheckAll(document.form1.selectedSKU)">Uncheck Selected (<script language="javascript">document.write($("input:checkbox:checked").length);</script>)</a>but the value always returned is 0. Is there something else I need to do or is it because I'm building the checkboxes as I've outlined in http://a.noma.li/n?
Liam
When you call document.write($("input:checkbox:checked").length, it writes a 0 to the document.
Zed
Oh yes, but should it update as I tick the boxes?
Liam
The call to $("input:checkbox:checked").length should update. But as I said, when you call document.write( ... ), then the call is once evaluated to 0 and the whole document.write( ... ) stuff is "replaced" with a 0, so $("input:checkbox:checked").length will never be called again.
Zed
Ok, so how would I go about writing the value to screen?
Liam
+5  A: 

Try this:

var inputElems = document.getElementsByTagName("input"),
    count = 0;
for (var i=0; i<inputElems.length; i++) {
    if (inputElems[i].type === "checkbox" && inputElems[i].checked === true) {
        count++;
    }
}
Gumbo