Pure Javascript to delete input fields

Asked

Viewed 40 times

0

Hello!

I’m starting web studies using pure javascript in the course I’m doing. In this exercise application, I was asked to insert a button to add more input fields, as needed by the user (this is a food recipe and the ingredient and preparation fields need as many lines as needed for each recipe). Until then I managed to do it correctly. The point is that I would like it to be possible to delete the lines. I put X next to the input that when clicked should delete the line. The most I could was to delete the first one. The following lines that were generated do not accept the command. I believe that the script loads at the beginning when I have only one line and does not reload to the next lines (line of reasoning of Noob rs). Could you help me? I can’t use jquery because the course doesn’t cover it.. Thank you!

SCRIPT

const stepRemove = document.querySelector(".remove-step")


stepRemove.addEventListener('click', function() {
    stepRemove.closest('div').remove();
})

HTML

<div class="item">
    <div class="input-title">Modo de preparo</div>
        <div id="steps">
            <div class="step">
                <input 
                    type="text" 
                    name="preparation[]"
                    value="{{recipe.preparation}}"
                >
                <a class="remove-step"><span class="material-icons">highlight_off</span></a>
            </div>
        </div>
    <button type="button" class="add-step">Adicionar novo passo</button>
</div>

Thanks for your help! Patrick

  • I know I shouldn’t do everything, but it was 10 funny minutes: https://jsbin.com/dipigov/3/edit?html,js,output

  • @balexandre share the answer and explain the code too, for sure will help

  • 1

    @balexandre thank you so much for the light. I took advantage much of your idea in solving my problem. Thanks!

1 answer

0


Hey there, Patrick boy! So I thought of the following solution: replace the old javascript code (because as you said it really only gets called once) for a function and add an onclick in the link.

Also, you should set a unique Id for each link, otherwise it will not work.

function removeDiv(id) {
		const stepRemove = document.getElementById(id)
		stepRemove.closest('div').remove();
	}
<div class="step">
  <input 
    type="text" 
    name="preparation[]"
    value="{{recipe.preparation}}"
  >
  <a id='id1' onclick="removeDiv(id)" class="remove-step"><span class="material-icons">highlight_off</span></a>
</div>

This way the value passed in onClick is already automatically set in the Link Id. Comment ai if it doesn’t work.

  • thank you so much for the help man. It did work. I did what you indicated to put an id in when creating. For this I used some of the idea of balexandre for this. But it worked super well. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.