0

in my validation the required fields can change. I have an array (required) of input ids which are required. If the array contains the string 'All' then all inputs are required.

I'm trying to use JQuery.inArray() to determine if required.

function getIfRequired(id){
    console.log("id: "+id);
    console.log(required);
    console.log("inarray: "+jQuery.inArray(required, 'All'));

    if (jQuery.inArray(required, 'All') > -1){ return true; }
    else if(jQuery.inArray(required, id) != -1){ return true; }
    else{ return false; }
}

But it keeps returning '-1' (not found).

here are example log outputs:

id: clientname
["clientname", "sourceid", "clientcountry","clienttown", "clienttownid", "typeoflaw"] 
inarray: -1 

id: clientname
["All"] 
inarray: -1 

Why is it not working?

8
  • Why do you send in 'All' instead of id? Also, the first argument should be the value and the second the array. Commented Sep 20, 2013 at 11:04
  • 1
    If you care to read the documentation you will notice that the method signature is inArray(value, array). ;) Commented Sep 20, 2013 at 11:05
  • 1
    facepalm - one day people will check function documentation before making up their own syntax and getting confused.. Commented Sep 20, 2013 at 11:06
  • facepalm indeed!!! Tbf I got the jquery.inarray line from existing code, never used it before. Teach me for assuming it was correct Commented Sep 20, 2013 at 11:09
  • @SmokeyPHP I highly doubt that this becomes a trend. :) Commented Sep 20, 2013 at 11:10

3 Answers 3

11

You have your value and array parameters transposed, e.g.:

jQuery.inArray('All', required);
Sign up to request clarification or add additional context in comments.

Comments

1

You call wrong jQuery.inArray. First goes the value and then the array

see http://api.jquery.com/jQuery.inArray/

write

jQuery.inArray('All', required);

instead of

jQuery.inArray(required, 'All');

Comments

0

because required not found in All

You will write as below

 console.log("inarray: "+jQuery.inArray('All', required));

Reference

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.