0

How to display an alert message when the values already present in an array using javascript

var names = [];

var nameInput = document.getElementById("txt1");
var messageBox = document.getElementById("display");

function insert() {
  names.push(nameInput.value);
  clearAndPush();
}

function clearAndPush() {
  nameInput.value = "";
  messageBox.innerHTML = "";
  messageBox.innerHTML += "Names:" + names.join(", ");

  function removeDups(names) {
    let unique = {};
    names.forEach(function(i) {
      if (!unique[i]) {
        unique[i] = true;
      }
    });
    return Object.keys(unique);
  }
  document.getElementById("display").innerHTML = removeDups(names);
}
<label>Name:</label><input type="text" id="txt1" placeholder="Enter Name">
<input type="button" value="Click" onclick="insert()">

<div id="display"></div>
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • You can use [`Array.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method it returns `boolean` i.e. `if( names.includes(nameInput.value)){ alert('Value exists'); }` – Satpal Dec 12 '18 at 07:17

1 Answers1

1

Your question is a little unclear, but (feel free to correct me) I believe that you want to check if a value is already in an array. That's extremely simple - use Array.prototype.includes():

if (names.includes(nameInput.value) {
    alert("The name " + nameInput.value + " is already in the names array.");
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • hi Jack Bashford i tried your code but it didn't work it out for me would you please give another solution for me... – Surendran P Dec 12 '18 at 08:20
  • That code works fine - I tested it. Please ensure you've got it in the right spot, and also look at the linked duplicates. – Jack Bashford Dec 12 '18 at 08:57
  • @SurendranP Array.prototype.includes() is supported from ES6 and here is link for supported browsers :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility – Ahmed Mostafa Dec 12 '18 at 09:42