添加到列表中

问题描述 投票:-2回答:2

我想使用javascript在用户点击按钮时将文本输入中的内容添加到列表中。到目前为止这是我的功能:

function add(){
    var form = document.getElementById('form')
    var email = form.elements.typer.value

    var select = document.getElementById('users')
    var option = document.createElement("option")
    option.text = email
    select.add(option)
}

它可以工作,但您可以多次添加相同的文本。如何制作程序以便用户不能多次添加相同的文本?

javascript html
2个回答
1
投票

您可以使用一个数组来跟踪已添加的所有电子邮件。然后,在创建select的选项之前,检查是否在该数组中找到它,如果没有,则添加,如果是,则告诉用户。

见下面的代码

var addedUsers = [];

function add(){
    var form = document.getElementById('form')
    var emailInput = form.elements.typer;
    let email = emailInput.value
    emailInput.value = "";

    if (addedUsers.indexOf(email) == -1){
      addedUsers.push(email)
      var select = document.getElementById('users');
      var option = document.createElement("option");
      option.text = email;
      select.add(option)
    } else {
      alert("This user is already in the list");
      emailInput.focus()
    }
}
<form id="form">
  <input id="typer"/>
  <button onclick="add()" type="button">Add</button>
</form>

<select id="users"></select>

0
投票

在添加文本之前,您可以使用includes()检查列表中是否已存在该文本。 MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

这将返回true或false,具体取决于值是否已存在于列表中。

© www.soinside.com 2019 - 2024. All rights reserved.