8

How can I search in an array to see if the value exists?

var fruitVarietyChecked = $('input[name=fruitVariety]:checked').val();

$.getJSON('getdata.php', {fruitVariety: fruitVarietyChecked}, function(fruittype) {

            var html = '';
            $.each(fruittype, function(index, array) {

                alert( "Key: " + index + ", Value: " + array['fruittype'] );
                //shows array - Key: 0 , Value: special item

                //this is where the problem is
                if ($(array.has("special item"))){

                    $("p").text("special item" + " found at " + index);
                    return false;
                    }

                html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
            });
            $('#fruittype').html(html);
            });
}

So far I tried .is , .has , .getdata and .inarray, but it's getting me nowhere.

The JSON call returns: [{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]

1
  • What does your array look like ? Commented Aug 31, 2011 at 19:47

2 Answers 2

24

I think its a syntax error: Change if ($(array.has("special item"))){ to

if ($.inArray("special item", array) > -1){ 

EDIT:

If the array has complex objects then you cannot use inArray, instead you can use the jQuery filter to achieve the same, e.g:

    var filtered = $(array).filter(function(){
        return this.fruittype == "special item";
    });
    if(filtered.length > 0){
Sign up to request clarification or add additional context in comments.

4 Comments

Although the answer is shown twice here, this does not seem to be working.
Can you post the array that is being returned by the JSON call?
The JSON call returns: [{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]
@Jroen: Updated the post please check.
2
if ( $.inArray(valueToMatch, theArray) > -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.