Pergunta

I'm trying to use jQuery to count ul li elements with a certain class. The class is being toggled on and off by another jQuery script:

 $(document).ready(function(){

$(".checkbox1").click(function(){
    $("li.tom").toggleClass( "hider" );
});
});

I understand that this means that I need to add an event handler to listen for changes in the ul:

 $('.cartlist').on('click', 'li.hider', function () {

    var total=$('.cartlist > li.hider').length;
        $('.totalCount').html('$' +total * 999); 
    }); });

The script I have written half works, in the sense that the .on() handler I am using successfully counts the class hider, but only when the li items are clicked. No doubt this is because I am using .on('click'). I've read the jQuery docs for .on() and, from what I understand, I should be able to use other DOM hooks like 'load', 'scroll' etc. However, when I replace .on('click') with .on('load') or .on('change'), nothing happens. Also, unchecking the checkboxes doesn't change the total, probably because the handler is tied to the ul and doesn't care about the checkboxes...

Fiddle

I am new here and new to jQuery so please forgive the obvious gaps in my knowledge. Thanks in anticipation for any replies.

Foi útil?

Solução

You were observing the UL and not the inputs:

$('.cartlist').on('click', 'li.hider', function () {...

If you instead observe the inputs, your method works:

$('form').on('click', 'input', function () {

Here is the JSFIDDLE: http://jsfiddle.net/C8nCf/

Outras dicas

Heres a method for counting elements that contain a specific class.

http://jsfiddle.net/bluey/2GZMY/ << JSfiddle

// Gets the number of elements with class yourClass
$( document ).ready(function() {
    var numItems = $('.thisClass').length;
    $('.howmany').html("counted: "+numItems);
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top