Есть ли хороший способ удалить соответствующую форму выбора? - PullRequest
0 голосов
/ 22 марта 2020

С этим кодом есть кнопка, где вы можете добавить выбор, это добавит 2 поля ввода и кнопку с X в нем, когда вы нажимаете кнопку x, я хочу удалить соответствующую форму выбора, Dose anybody Имейте хорошую идею о том, как это сделать

 //adds more selection forms 
  var selectionAmmount = 0;
  var div;
  function addSelection() {
    var div = document.createElement('div')
    div.innerHTML = '<br>' + 
        '<input type="text" placeholder="Name Of selection">' + '<br>' +
        '<input type="number" placeholder="Price per s.y"">' + '<input type="button" value="x" onClick="removeSelection()">' + '<br>';

    document.getElementById("addSelection").appendChild(div);
    selectionAmmount++;
  }

  function removeSelection(t) {
    document.getElementById("addSelection").removeChild(document.getElementById("addSelection").childNodes[selectionAmmount - 1]);
    selectionAmmount--;
  }
 <div>
Has a selection: <input type="checkbox" id="selection" checked><br><br>
<selection id="hideSelection">
  <input type="text" placeholder="Name Of selection" id="selectionName"><br>
  <input type="number" placeholder="Price per s.y" id="selectionPrice"><br>
  <selection id="addSelection"></selection>   
  <input type="button" value="+ selection" onclick="addSelection()"><br><br>
</selection>

Это ссылка на хостинг кода, если вы хотите увидеть его в действии: https://ogdens-flooring-estimator.hunterscott1.repl.co/carpet.html

Если это будет полезно, я также могу опубликовать весь файл целиком, просто дайте мне знать, что я очень признателен за любую помощь :)

1 Ответ

0 голосов
/ 22 марта 2020

Назначьте id для div , который вы создаете в addSelection ()

 div.id=`selection${id}`; 

В кнопке при нажатии передайте id

onClick="removeSelection(${id})"

В функцию removeSelection , получите элемент по этому id и удалите его.

document.getElementById(`selection${id}`).remove();

Запустите следующий фрагмент.

var selectionAmmount = 0;
var id=1;
var div;
function addSelection() {
  var div = document.createElement('div')
  div.innerHTML = `<br><input type="text" placeholder="Name Of selection"><br><input type="number" placeholder="Price per s.y""><input type="button" value="x" onClick="removeSelection(${id})"><br>`;
  div.id=`selection${id}`;    
  document.getElementById("addSelection").appendChild(div);
  selectionAmmount++;
  id++;
}

function removeSelection(id) { 
  selectionAmmount--;
  document.getElementById(`selection${id}`).remove();
}
<div>
Has a selection: <input type="checkbox" id="selection" checked><br><br>
<selection id="hideSelection">
  <input type="text" placeholder="Name Of selection" id="selectionName"><br>
  <input type="number" placeholder="Price per s.y" id="selectionPrice"><br>
  <selection id="addSelection"></selection>   
  <input type="button" value="+ selection" onclick="addSelection()"><br><br>
</selection>
...