0

My goal is display alert message if varible test is the same as the one item of the array active.

<p id="user">Steve Jobs</p>

var test = $("#user").text();

var active = [
  "Steve Jobs",
  "Steve Wozniak",
  "Tim Cook"
]

if ( test === active ) {
  alert ("match");
}

How can I make it? Why my script doesn't work?

Karolina Ticha
  • 531
  • 4
  • 19
  • 1
    [Google it first](https://www.google.com/search?q=javascript+how+to+find+if+an+array+contains+a+value&oq=javascript+how+to+find+if+an+array+contains+a+value&aqs=chrome..69i57j0l2.11567j0j4&sourceid=chrome&ie=utf-8&safe=active&gws_rd=ssl) – 4castle Jul 14 '16 at 19:27
  • "*Why my script doesn't work?*" - your script *does* work, it's just that `test` does not exactly equal `active`; because one is a string and the other is an array. – David Thomas Jul 14 '16 at 19:29
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – 4castle Jul 14 '16 at 19:31
  • @Karolina Ticha: Were you able to resolve this? If so, please remember to accept an answer and upvote. – poppertech Jul 19 '16 at 22:31

3 Answers3

0

Right now you are testing whether "Steve Jobs" is identical to the array active. You could use $.inArray(test, active); to determine whether "Steve Jobs" is in the active array.

poppertech
  • 1,286
  • 2
  • 9
  • 17
0
var test = $("#user").text();

var active = [
  "Steve Jobs",
  "Steve Wozniak",
  "Tim Cook"
]

if ( $.inarray(test, active) >= 0 ) {
  alert ("match");
}

$.inarray() returns the index of the value that has a match.

Nagaraj Raveendran
  • 1,150
  • 15
  • 23
0

In javascript to check an array having a value or not we can use funcion $.inArray(). Please look in to below code.

<p id="user">Steve Jobs</p>

var test = $("#user").text();

var active = [
  "Steve Jobs",
  "Steve Wozniak",
  "Tim Cook"
]

if ($.inArray( test, active )) {
  alert ("match");
}
Rahul Patel
  • 5,248
  • 2
  • 14
  • 26
  • I have checked code.Please use following condition it will work. if ($.inArray( test, active )>=0) { console.log ("match"); } – Rahul Patel Jul 15 '16 at 06:04