Проблема в добавлении / удалении элемента из списка данных дважды или более - PullRequest
0 голосов
/ 04 апреля 2020

Добрый вечер всем, поэтому я пытаюсь позволить пользователю добавить список ингредиентов. есть текстовый ввод, где он может либо ввести имя ингредиента, либо выбрать из списка предложений (я использовал ввод с datalist). Когда он нажимает кнопку добавления, элемент добавляется в список и удаляется из списка предложений (список данных). когда он удаляет элемент из списка, он удаляется из списка ингредиентов и возвращается обратно в список предложений. обычно это выглядит так: добавление ингредиентов Код работает хорошо, но только в первый раз. когда пользователь удаляет элемент из списка ингредиентов, а затем выбирает элемент для добавления снова, он не удаляется из списка предложений. Я думаю, что это проблема в функции «возврата».

вот фрагменты кода (попробуйте добавить в ингредиенты любой элемент, такой как "plasti c bags", затем удалите его и добавьте снова):

function removeItem(list) { //removes item from suggestions list
  var item = $('input#' + list).val();
  if ($('option[value="' + item + '"]'))
    $('option[value="' + item + '"]').remove();
}


function returnItem(e) { //returns item to suggestions list
  var optionVal = $(e).closest("td").next().children("label").html();
  var newOption = new Option(optionVal);
  $("#suggests").append(newOption);
}


function addIngredient(e) { //adds item to ingredient list
  var inputContent = document.getElementById("addIngreField").value;
  if (inputContent != "") {
    var table = document.getElementById("ingredients");
    var row = table.insertRow(table.rows.length - 1);
    var cell1 = row.insertCell(0);
    cell1.style.textAlign = "left";
    cell1.innerHTML = "<input class='removeIngre' type='button' value='-' onclick='returnItem(this) ; removeIngredient(this)'>";
    var cell2 = row.insertCell(1);
    cell2.innerHTML = "<label class='ingred'>" + inputContent + "</label>";
    document.getElementById("addIngreField").value = "";
  }
};


function removeIngredient(e) { //removes item from ingredients list
  var row = e.parentNode.parentNode;
  row.parentNode.removeChild(row);
}
.ingred {
  display: block;
  position: relative;
  width: 200px;
  margin-bottom: 12px;
  font-size: 20px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  color: black;
  font-family: "Muli-Reg";
}

.addIngre {
  cursor: pointer;
  outline: none;
  height: 30px;
  width: 30px;
  border-radius: 50%;
  border: none;
  background-color: green;
  line-height: 5px;
  color: white;
  font-size: 18px;
  font-weight: bold;
  font-family: "Muli-Reg";
}

.removeIngre {
  cursor: pointer;
  outline: none;
  height: 30px;
  width: 30px;
  border-radius: 50%;
  border: none;
  background-color: #cc0000;
  line-height: 5px;
  color: white;
  font-size: 18px;
  font-weight: bold;
  font-family: "Muli-Reg";
}

.addSte {
  cursor: pointer;
  outline: none;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: none;
  background-color: green;
  color: white;
  font-size: 18px;
  font-weight: bold
}

.removeSte {
  cursor: pointer;
  outline: none;
  opacity: 0.5;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: none;
  background-color: #cc0000;
  color: white;
  font-size: 18px;
  font-weight: bold
}

.removeIngre:hover {
  opacity: 1;
}

.removeSte:hover {
  opacity: 1;
}

#add {
  cursor: pointer;
}

#stepsTable {
  counter-reset: row-num;
}

#stepsTable tr {
  counter-increment: row-num;
}

#stepsTable tr td:nth-child(2)::before {
  content: counter(row-num);
}

input:focus::-webkit-input-placeholder {
  color: transparent;
}

input:focus:-moz-placeholder {
  color: transparent;
}


/* FF 4-18 */

input:focus::-moz-placeholder {
  color: transparent;
}


/* FF 19+ */

input:focus:-ms-input-placeholder {
  color: transparent;
}


/* IE 10+ */

textarea:focus::-webkit-input-placeholder {
  color: transparent;
}

textarea:focus:-moz-placeholder {
  color: transparent;
}


/* FF 4-18 */

textarea:focus::-moz-placeholder {
  color: transparent;
}


/* FF 19+ */

textarea:focus:-ms-input-placeholder {
  color: transparent;
}


/* IE 10+ */
<link rel="stylesheet" type="text/css" href="CSS/Navigation-visitor.css">
<link rel="stylesheet" type="text/css" href="CSS/addArtwork.css">
<link rel="stylesheet" type="text/css" href="CSS/footer.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="JS/jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="JS/menuBar.js"></script>

<table id="ingredients" style="text-align: left; margin: auto; width:400px; font-family: " Muli-Reg ";">

  <tr>
    <td colspan="2">
      <p class="fieldTitle" style="color: gray; font-size: 22px;">Ingredients</p>
    </td>
  </tr>

  <tr id="addI">
    <td style="text-align: left; width: 50px;">
      <input class="addIngre" type="button" value="+" onclick="removeItem('addIngreField'); addIngredient()">
    </td>
    <td>
      <input id="addIngreField" type="text" maxlength="300" style="border: solid black; padding-left: 10px; padding-right: 10px; outline: none;  border-radius: 20px; font-size: 15px; height: 30px; width: 95%; text-align:left" list="suggests">

      <datalist id="suggests">
                <option value="Plastic Bags">
                <option value="colored paper">
                <option value="wood frames">
                <option value="Used Fabrics">
                <option value="Terapak Cartons">
                <option value="Hair ties">
                <option value="Newspaper">
                <option value="Cardboards">
                <option value="Pizza Box">
                <option value="Aluminum Foil">
                <option value="Cloth Hangers">
                <option value="CD's">
                <option value="Leather">
              </datalist>
    </td>
  </tr>


  <tr>
    <td colspan="2" style="text-align: right; height: 50px;">
      <button style="border: none; border-radius: 10px; height: 40px; width: 80px; color: dimgrey; font-size: 22px; background-color: darkgrey; " class="fieldTitle">next</button>
    </td>
  </tr>
  
</table>

1 Ответ

1 голос
/ 04 апреля 2020

Вам необходимо добавить атрибут value при повторном создании опции. new Option(optionVal, optionVal)

function removeItem(list) { //removes item from suggestions list
  var item = $('input#' + list).val();
  if ($('option[value="' + item + '"]'))
    $('option[value="' + item + '"]').remove();
}


function returnItem(e) { //returns item to suggestions list
  var optionVal = $(e).closest("td").next().children("label").html();
  var newOption = new Option(optionVal, optionVal);
  $("#suggests").append(newOption);
}


function addIngredient(e) { //adds item to ingredient list
  var inputContent = document.getElementById("addIngreField").value;
  if (inputContent != "") {
    var table = document.getElementById("ingredients");
    var row = table.insertRow(table.rows.length - 1);
    var cell1 = row.insertCell(0);
    cell1.style.textAlign = "left";
    cell1.innerHTML = "<input class='removeIngre' type='button' value='-' onclick='returnItem(this) ; removeIngredient(this)'>";
    var cell2 = row.insertCell(1);
    cell2.innerHTML = "<label class='ingred'>" + inputContent + "</label>";
    document.getElementById("addIngreField").value = "";
  }
};


function removeIngredient(e) { //removes item from ingredients list
  var row = e.parentNode.parentNode;
  row.parentNode.removeChild(row);
}
.ingred {
  display: block;
  position: relative;
  width: 200px;
  margin-bottom: 12px;
  font-size: 20px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  color: black;
  font-family: "Muli-Reg";
}

.addIngre {
  cursor: pointer;
  outline: none;
  height: 30px;
  width: 30px;
  border-radius: 50%;
  border: none;
  background-color: green;
  line-height: 5px;
  color: white;
  font-size: 18px;
  font-weight: bold;
  font-family: "Muli-Reg";
}

.removeIngre {
  cursor: pointer;
  outline: none;
  height: 30px;
  width: 30px;
  border-radius: 50%;
  border: none;
  background-color: #cc0000;
  line-height: 5px;
  color: white;
  font-size: 18px;
  font-weight: bold;
  font-family: "Muli-Reg";
}

.addSte {
  cursor: pointer;
  outline: none;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: none;
  background-color: green;
  color: white;
  font-size: 18px;
  font-weight: bold
}

.removeSte {
  cursor: pointer;
  outline: none;
  opacity: 0.5;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: none;
  background-color: #cc0000;
  color: white;
  font-size: 18px;
  font-weight: bold
}

.removeIngre:hover {
  opacity: 1;
}

.removeSte:hover {
  opacity: 1;
}

#add {
  cursor: pointer;
}

#stepsTable {
  counter-reset: row-num;
}

#stepsTable tr {
  counter-increment: row-num;
}

#stepsTable tr td:nth-child(2)::before {
  content: counter(row-num);
}

input:focus::-webkit-input-placeholder {
  color: transparent;
}

input:focus:-moz-placeholder {
  color: transparent;
}


/* FF 4-18 */

input:focus::-moz-placeholder {
  color: transparent;
}


/* FF 19+ */

input:focus:-ms-input-placeholder {
  color: transparent;
}


/* IE 10+ */

textarea:focus::-webkit-input-placeholder {
  color: transparent;
}

textarea:focus:-moz-placeholder {
  color: transparent;
}


/* FF 4-18 */

textarea:focus::-moz-placeholder {
  color: transparent;
}


/* FF 19+ */

textarea:focus:-ms-input-placeholder {
  color: transparent;
}


/* IE 10+ */
<link rel="stylesheet" type="text/css" href="CSS/Navigation-visitor.css">
<link rel="stylesheet" type="text/css" href="CSS/addArtwork.css">
<link rel="stylesheet" type="text/css" href="CSS/footer.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="JS/jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="JS/menuBar.js"></script>

<table id="ingredients" style="text-align: left; margin: auto; width:400px; font-family: " Muli-Reg ";">

  <tr>
    <td colspan="2">
      <p class="fieldTitle" style="color: gray; font-size: 22px;">Ingredients</p>
    </td>
  </tr>

  <tr id="addI">
    <td style="text-align: left; width: 50px;">
      <input class="addIngre" type="button" value="+" onclick="removeItem('addIngreField'); addIngredient()">
    </td>
    <td>
      <input id="addIngreField" type="text" maxlength="300" style="border: solid black; padding-left: 10px; padding-right: 10px; outline: none;  border-radius: 20px; font-size: 15px; height: 30px; width: 95%; text-align:left" list="suggests">

      <datalist id="suggests">
                <option value="Plastic Bags">
                <option value="colored paper">
                <option value="wood frames">
                <option value="Used Fabrics">
                <option value="Terapak Cartons">
                <option value="Hair ties">
                <option value="Newspaper">
                <option value="Cardboards">
                <option value="Pizza Box">
                <option value="Aluminum Foil">
                <option value="Cloth Hangers">
                <option value="CD's">
                <option value="Leather">
              </datalist>
    </td>
  </tr>


  <tr>
    <td colspan="2" style="text-align: right; height: 50px;">
      <button style="border: none; border-radius: 10px; height: 40px; width: 80px; color: dimgrey; font-size: 22px; background-color: darkgrey; " class="fieldTitle">next</button>
    </td>
  </tr>
  
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...