Adding or removing html elements dinamically

Lately I had been blowing me out my head thinking on how I figure out a particular way to add and remove a bunch of rows of elements there is in the DOM (Document Object Model). Definitely I’ve realize that the only effective way to do this task is making it through JavaScript, but if you import libraries like jQuery, it become easier to accomplish it.
We must understand first off that this could be useful when you need adding some extra fields into a main form before hit on submit button, but, it requires to keep in mind some concepts in order to avoid user will do strange things to your dynamic form.

Consider a variable that allow to count how many divs they have added already, since you need to decrease it, when it’s clicked on remove button, with no further ado, the following code snippet I’m going to define the html skeleton:

<button class="add-inputs">Add more fields</button>  
<div class="row-inputs">  
    <div><input type="text" /> <button class="remove_field">Remove</button></div>
</div>  

For reason of explaining the needed logic to understand this example, jquery library is important to navigate through the DOM, you can import whatever version you want as long as from 2.x

$(document).on('ready', init)
var rows = $(".row-inputs div")  
var inputs = rows.parent().html().trim() // we must save state only when the page's loaded

function init()  
{
    var counts = 1; // this is the starter value of quantity of inputs there are.
    $(".add-inputs").on('click', function(e){
        e.preventDefault()
        $(".row-inputs").append(inputs)
        counts++
    })

    $(".row-inputs").on('click', '.remove_field', function(e) {
        e.preventDefault()
        if (counts > 1) {
            $(this).parent().remove()
            counts--
        }
    })
}

And you’re done! Now you know how to add or remove whatever you want dynamically-way and you’re ready for use this snippet in your apps out there.
Wanna see this code in-action? There, surely I can show you.

Any doubt you have feel free leave in the comments below and it’d be a pleasure help you.

Leave a Reply