0

I want to get result from array and check it one by one

//////////////////////////////////////////////
//////////// this code not works,  ////////////
////////////   but not flexible   ////////////
//////////////////////////////////////////////

var myA = ["said", "imad", "hassan", "bilal", "mohamed"];
var doc = document.getElementById('div1');
var inp = document.getElementById('input1');

function click1() {
    'use strict';

    var i = inp.value;

    if (i <= 0) {
    doc.innerHTML = 'Please type name';

    } else if (i === myA[0] || i === myA[1] ||
           i === myA[2] || i === myA[3] || i === myA[4]) {
    doc.innerHTML = i;

    } else {
    doc.innerHTML = 'Please type in a correct name';
    }
}


/////////////////////////////////////////////////////
//////////// my try to make it flexible, ////////////
//////////// but i get just a last index ////////////
/////////////////////////////////////////////////////


var myA = ["said", "imad", "hassan", "bilal", "mohamed"];
var index = myA[0];
// console.log(index);
var doc = document.getElementById('div1');
var inp = document.getElementById('input1');

function getId(a){
  var aL = a.length, index = a[0], x=0;

  for(x = 0; x < aL; x++ ){
  index = a[x];
  // console.log(index);
  }    
  return index;
}  
// console.log(getId(myA));

function click1() {
  'use strict';

  var i = inp.value;

  if (i <= 0) {
  doc.innerHTML = 'Please type name';

  } else if (i === getId(myA)) {
  doc.innerHTML = i;

  } else {
  doc.innerHTML = 'Please type in a correct name';
  }
}
Eldelshell
  • 6,683
  • 7
  • 44
  • 63
said kot
  • 15
  • 4
  • 1
    I would suggest that rather than link to all of your code, you include relevant snippets here and show the actual output vs the expected output. People will be more likely to help. – brandonx Apr 09 '19 at 22:49
  • 1
    Your code should be included **in the question**, not in an external page. Also, rather than trying to check each result just use `myA.includes(i)`. See [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/q/237104/1715579) – p.s.w.g Apr 09 '19 at 22:55

2 Answers2

0

Your getId() function is simply wrong. The way it's designed, it's looping over your myA array and always returns the last element: mohamed. You need to feed this function a value to compare, loop over the array and in case it finds a match, return a boolean true. If not make it return false.

function getId(val){
  for(var a=0;a<myA.length;a++)
  {
    if(myA[a]==val)
    {
      return true;
    }
  }
  return false;
}

Now you can simply call it by

if (getId(i)) {
      doc.innerHTML = i;

  } else {
      doc.innerHTML = 'Please type in a correct name';
  }
obscure
  • 11,916
  • 2
  • 17
  • 36
0

How to check if a value is in an array:

New style (ES6):

if (myA.includes(inp.value)) {
  // name found in array
}

Older style:

if (myA.indexOf(inp.value) > -1) {
  // name found in array
}
James
  • 20,957
  • 5
  • 26
  • 41