0

I have a dropdown menu that contains checkboxes, and more than one can be checked at once. When a checkbox is selected, it's label's class is set to "checked" and then removed when it is deselected.

Before checkbox is selected:

<label><input type="checkbox" name="gainlosstypes[]" value="Losses" class="upperFilter">Losses</label>

After checkbox is selected:

<label class="checked"><input type="checkbox" name="gainlosstypes[]" value="Losses" class="upperFilte">Losses</label>

When it is selected the label element has .toggleClass('checked') called on it.

I need to be able to detect which label's have their class set to "checked" so that I can filter data based on those fields.

If $(this) is the label element, when I try $(this).hasClass('checked') it throws an error. That's the only way I know to try. Is there some other way to tell if a specific label element has a specific class?

Edit:

I get these errors when trying to check for the attribute. It also happens when I use hasClass:

> $(".multiSelectOptions :checkbox")[1].attr('checked')
TypeError: Object #<HTMLInputElement> has no method 'attr'
> $(".multiSelectOptions :checkbox").parent('label')[1].attr('checked')
TypeError: Object #<HTMLLabelElement> has no method 'attr'
Saliceran
  • 330
  • 1
  • 7
  • 26

3 Answers3

1

Checked is not a css class it is an html attribute. thus you should check for the attribute not the class.

You should try :

if($(this).attr('checked') != null)
{
    //do stuff here
}

EDIT:

Like @Bojangles said checked could be a custom CSS class but it would probably make more sense to check for checked checkbox with the attribute rather than a custom css class.

EDIT #2:

PLEASE SKIP PREVIOUS ANSWER AND USE THIS INSTEAD:

You could use the JQuery selector on this:

For exemple:

$('.checked')//this would get you all the element with the class 'checked'

//if you want to check if you have any check element:

if($('.checked').length > 0)
{
    //do stuff here
}

//To loop trought all the element that are 'checked'

$('.checked').each(
function(index)
{
    $(this).removeClass('checked');
    //do stuff here for exemple...
}
)
Sebastien
  • 1,308
  • 2
  • 15
  • 39
-2

This will set checked if the label has the attribute 'checked' set, otherwise you'll get undefined and can base your logic off this.

var checked = $(this).attr('checked');
Brian Maupin
  • 745
  • 4
  • 17
-2

How about

if( $(this).attr('class') == "checked" ){
    ... do something
}

That will check for the class of checked . . .

Pat Dobson
  • 3,249
  • 2
  • 19
  • 32