开发者

How to check if string is .inarray

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 cont开发者_如何学运维ained within the array if it is I want to .show a li

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


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.


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

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


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()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜