0

My inArray jQuery verification dosen't work :

The html :

<input type="text" name="number" class="verify" conditions="requierd numeric"/>
<input type="text" name="number2" class="verify" conditions="requierd string"/>

The jQuery code with my inArray verification :

    $('input.verify').blur(function(){
        var conditions = $(this).attr('conditions').split(' ');
            if($.inArray('requierd', conditions)){
                alert('ok');
            }
    });

but when i put === false behind my condition it work !

    $('input.verify').blur(function(){
        var conditions = $(this).attr('conditions').split(' ');
            if($.inArray('requierd', conditions) === false){
                alert('ok');
            }
    });

Why ?

Thanks

3 Answers 3

1

Official documentation says:

returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

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

Comments

0

Like with indexOf(), $.inArray must be checked against -1. Otherwise, if the element is not found, it will return -1 which i s a truthy value, i.e. it will resolve your condition to true.

In short:

if ($.inArray('something', array) != -1)

Note though that you don't really need to split the conditions string - you could use a REGEX with a word boundary.

if (/\brequired\b/.test($(this).attr('conditions')) { /* code */ }

Finally, you should use data- attributes rather than just inventing custom attributes, as the latter will invalidate your HTML.

Comments

0

$.inArray() will return -1 if the element is not found, which will evaluate to true. Either use:

if (~$.inArray('requierd', conditions))

This will work because ~-1 == 0 == false. Or, as an alternative, and by far the most common:

if ($.inArray('requierd', conditions) != -1)

Comments

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.