0

I am trying to find some words in some array and I did something like this:

    $("#get").click(function(){
    $(".name").each(function(){
        var fisier = $(this).text();
        alert($.inArray("migr", fisier));
    });
});

I have "migr" in almost every fisier var but I get only -1. What am I doing wrong ?

Thanks!

arrd
  • 41
  • 8

4 Answers4

1

With the help of inArray function you can check value exists in array or not. $.inArray function return the index of element. If element not exist in array it will return -1. So, we can check it very simply weather a value exist in array or not.

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
1

inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array.

So, to check if an item is in the array, use:

if(jQuery.inArray("test", myarray)!==-1) 

or

if($.inArray("test", myarray)!==-1) 

as inArray will return -1, if the element was not found.

Furquan Khan
  • 1,586
  • 1
  • 15
  • 30
  • 1
    If you want to return a boolean, use a tilde (~). `if (!~$.inArray(0, [1, 2, 3, 4, 5])) { // returns false, not -1 }`. – Martin James Jun 21 '18 at 12:40
1

You could check for the keyword with JavaScript indexOf method. This is check for each element of the array:

$("#get").click(function(){
    $(".name").each(function(){
        var fisier = $(this).text();       
        if(fisier.indexOf("migr") !=-1){
           alert('Keyword found');
        }else{
           alert('Keyword not found');
        } 
    });
});
gradosevic
  • 4,809
  • 2
  • 36
  • 51
0

fisier is just a string not an array.

I guess this is what you want:

$("#get").click(function(){
    var names = $('.name').map(function() {
        return $(this).text();
    });
    alert($.inArray("migr", names));
});
xdazz
  • 158,678
  • 38
  • 247
  • 274