mercredi 22 novembre 2017

javascript/jQuery: for loop - check if string exist then add to list, otherwise alert user

I have a list and I need to check if an item exist. if not exist add to list, if exist alert user then exit. This is the code:

HTML

    <input type="text" placeholder="Add New Item">
    <ul>
        <li> Go to home</li>
        <li> Buy cavolo</li>
        <li> Fried chicken</li>
    </ul>

JS

$("input[type='text']").keypress(function(event) {
  if (event.which === 13) {
    var todoText = " " + $(this).val();
    var lis = $("li");
    for (var i = 0; i < lis.length; i++) {
      if (lis[i].textContent === todoText) {
        //check if todo exist
        //console.log("exist");
        alert("todo exist!");
      } else {
        //console.log("do not exist");
        $("ul").append("<li>" + todoText + "</li>");
      }
    }
  }
});

thanx

Aucun commentaire:

Enregistrer un commentaire