tags:

views:

116

answers:

1

Hi folks,

I am trying to use jQuery each() to iterate across a group of checkboxes named supplier_type[]. They all have unique ids so I could just re-write this to handle an array of unique ids but I wanted to figure out where I went wrong here.

The alert shows that while intIndex sees the correct number of elements this always holds the first element.

function setUp(){
    $( 'input[name=supplier_type[]]' ).each(
        function( intIndex ){
            var type = $(this+':checked').val() + 'Table';
            $("#"+type).show("slow");
            alert($(this+':checked').val());  // sees first one each iter
        }       
    );
}

So how do I address the correct element? Do I need to use bind()?

Thanks!

JG

// Edit Working version based on Drew Wills response. Thanks Drew!

function setUp(){
    $( 'input[name=supplier_type[]]' ).each(
        function( intIndex ){
            if($(this).attr('checked')) {
                var type = $(this).val() + 'Table';
                $("#"+type).show("slow");
            }
        }       
    );
}
+2  A: 

I'm not sure I understand your question 100%, but I'm very suspicious of the following style of selector:

$(this+':checked')

I'm guessing you want to know the value of the 'checked' attribute, which would be more like...

$(this).attr('checked')
Drew Wills
Thanks for the reply. Am I misusing this? http://api.jquery.com/checked-selector/
jerrygarciuh
The ':checked' selector matches instances that are checked, it doesn't tell you whether a given instance is checked or not. What do you get if you do alert(this+':checked')? I'm surprised that this concatenated string matches anything at all.
Drew Wills
nice catch on the selector
Vinodh Ramasubramanian