0

Ok, so I have this jquery function to that grabs the checkbox's value and uses as identifier to show or hide an ul

The problem is that I couldn't manage to add an if only 1 choice in checkbox add X.

Here is the code and what I have tried

$('#filter li input:checkbox').change(
    function(){
        var show = $('input:checkbox:checked').map(function(){
           return $(this).val();
        });
        if (show.length > 0)
        {
                $('#list li').each(
                function(){
                    /*if ($.inArray($(this).attr('class'),show) <= 1)
                    {
                        console.log($(this));
                    }
                    else */if ($.inArray($(this).attr('class'),show) > -1)
                    {                        
                        $(this).show();
                    }
                    else
                    {
                        $(this).hide();
                    }
                });
        }
        else {
            $('#list li').show();
        }
    });

I don't really understand how this works: if ($.inArray($(this).attr('class'),show) > -1) because I have tried if ($.inArray($(this).attr('class'),show) = 1) and nothing

1 Answer 1

2

You're assigning a value in the if clause:

if ($.inArray($(this).attr('class'),show) = 1)

To break it down, what this is actually saying is equivalent to

$.inArray($(this).attr('class'),show) = 1;
if ($.inArray($(this).attr('class'),show))
{
    ...

You should use the == comparison operator

if ($.inArray($(this).attr('class'),show) == 1)

Or, more correctly avoiding type coersion, use ===

if ($.inArray($(this).attr('class'),show) === 1)

This will avoid comparison between 1 and "1" returning true

Sign up to request clarification or add additional context in comments.

4 Comments

sorry, I should've removed that before posting... it is not the case... I need to fix the if inside $('#list li').each(...
Errrr, well, same applies. Use the === instead. if ($.inArray($(this).attr('class'),show) === 1)
for some reason it doesn't work. I have tried if ($.inArray($(this).attr('class'),show) == 1) and also === 1 and the alert that I added doesn't popup
Well, what is the value of the thing you are checking. I.e. do alert($.inArray($(this).attr('class'),show) ) and see what you get. If it is equal to 0,2,3,4, etc then the condition will not be met.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.