简体   繁体   中英

How can I detect if a label has a specific class?

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'

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...
}
)

如果标签的属性设置为“ checked”,这将设置为checked,否则您将无法定义并且可以根据此逻辑。

var checked = $(this).attr('checked');

How about

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

That will check for the class of checked . . .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM