简体   繁体   中英

index not incrementing in input field

I have a button that creates two input fields on click. I want to add a unique id for each couple of inputs that is created so that I can delete them later. Currently when I add the inputs they all have the same id 0 and the index does not increment, why and how can I make it increment? Here is my code:

 createNewPricedRoundShareholder() {

  
    const mainParent = document.getElementById('main-parent');
    var index = 0;

    const newPlatformNameInput1 = document.createElement("input");
  newPlatformNameInput1.id = index + '_first';
  newPlatformNameInput1.value = index;
  const newPlatformNameInput2 = document.createElement("input");
  newPlatformNameInput2.id = index + '_second';
  newPlatformNameInput2.value = index;
  const deleteButton = document.createElement("button");
  deleteButton.innerText = 'delete';
  const wrapperParent = document.createElement('div');
  wrapperParent.id = index + '_parent';
  wrapperParent.appendChild(newPlatformNameInput1);
  wrapperParent.appendChild(newPlatformNameInput2);
  wrapperParent.appendChild(deleteButton);  mainParent.appendChild(wrapperParent);
  index++;
    

    }

and my html:

<div id="main-parent"></div>

I know you said you want an ID so you can use it to delete your row later, but you don't actually need it. If you add this code to your function, you can delete the entire row without the need of using an ID. This code will allow you to target the specific button, then the parent of that button and remove it.

deleteButton.addEventListener("click",function(e){
  e.preventDefault();
  e.target.parentNode.remove();
});

I think that is because you increase the index at the end of your function but you should increase it after creating the first input and before creating the second one

    [...]
    const newPlatformNameInput1 = document.createElement("input");
    newPlatformNameInput1.id = index + '_first';
    newPlatformNameInput1.value = index;
    index++;
    const newPlatformNameInput2 = document.createElement("input");
    newPlatformNameInput2.id = index + '_second';
    [...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM