1

How can I check if a string is contained with my array? Here's how I'm putting the array together...

 // get the select
 var $dd = $('#product-variants');

 if ($dd.length > 0) { // make sure we found the select we were looking for

 // save the selected value
 var selectedVal = $dd.val();

 // get the options and loop through them
 var $options = $('option', $dd);
 var arrVals = [];
 $options.each(function(){
     // push each option value and text into an array
     arrVals.push({
         val: $(this).val(),
         text: $(this).text()
     });
 });
};

I want to check if "Kelly Green" is contained within the array if it is I want to .show a li

$("#select-by-color-list li#kelly-green").show();

3 Answers 3

4

The other answers are correct so far as use $.inArray() here, however the usage is off, it should be:

if($.inArray('Kelly Green', arrVals) != -1) {
  $("#select-by-color-list li#kelly-green").show();
}

$.inArray() returns the position in the array (which may be 0 if it's first...so it's in there, but that if() would be false). To check if it's present, use != -1, which is what it'll return if the element is not found.

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

Comments

1

You can use jQuery's inbuilt .inArray() method:

if($.inArray('Kelly Green', arrVals) != -1) {
    $("#select-by-color-list li#kelly-green").show();
}

2 Comments

Be careful using this, the check is incorrect, it should be if($.inArray('Kelly Green', arrVals) != -1) {, 0 is a valid result, if the element is the first in the array you'll get 0, -1 is what you should be checking for.
@Nick Craver, you're right, I've fixed the answer. I naturally assumed that jQuery would not duplicate JS's own idiocies and would return rather just a boolean value indicating the precense of a value. :)
1

Try this:

console.log($.inArray('Kelly Green', arrVals);

if($.inArray('Kelly Green', arrVals)
{
  $("#select-by-color-list li#kelly-green").show();
}

Possible dupe: Need help regarding jQuery $.inArray()

2 Comments

You got the parameters wrong way around, it's .inArray(value, array).
@ Noah and Tatu, Nice one! I was thinking about it to hard! Works great! Thanks very much

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.