-1

I have this array that searches for matches between two arrays. The problem is that it only returns one match and completes. I would like it to return all matches.

Does anyone know why this is only returning once?

var arr1 = $("li a");
var arr2 = $("input").attr('value').split(',');
$.each(arr1, function(i, val) {
  if ($.inArray($(val).html(), arr2) !== -1) {
    // alert('You got a match!')
  }
});

Relevant HTML code:

<input value="Bob Marley, Bob Hanson, Bob Smith" />
<li><a href=#">Bob Marley</a></li>
<li><a href=#">Jeff CookieMonster</a></li>
<li><a href="#">Bob Hanson</a></li>
Trip
  • 26,756
  • 46
  • 158
  • 277

2 Answers2

3

Spaces issue [untested]

"Bob Marley, Bob Hanson, Bob Smith" splitted by "," 


= [ "Bob Marley", "_Bob Hanson", "_Bob Smith" ]
Dogbert
  • 212,659
  • 41
  • 396
  • 397
Pedro Ferreira
  • 629
  • 3
  • 8
1

There is a space after the comas in yout input. So only the first value is found.

You have to trim the values after splitting the string.

Trim string in JavaScript? for more information on how to trim.

Community
  • 1
  • 1
Samuel Rossille
  • 18,940
  • 18
  • 62
  • 90