Dynamically Add or Remove Input Elements

add remove input elements

This tutorial will show you how to dynamically add or remove an input element in your web pages

First let us create one input component which consist of a radio button and textarea inside a container div


<div id="container">

    <div style="float:left; margin-right:10px;">
        <input type="radio">
    </div>

    <textarea placeholder="TextBox 1" rows="2"></textarea>

    <div style="clear:both;"></div>

</div>

And now create the add and remove buttons


<input type="button" name="plus" id="plus" value="+">
<input type="button" name="minus" id="minus" value="-">

Now we need to write the codes for the button clicks to add or remove the components

First, for the add button we will append the same input component we said above on every button click

We will keep a counter ‘i’ for this starting with 2


i=2;
$('#plus').click(function(){
    $('#container').append('<div style="float:left; margin-right:10px;"><input type="radio"></div><textarea placeholder="TextBox '+i+'" rows="2"></textarea><div style="clear:both;"></div></div>');
    i++;
});

And for the remove button, we will get all the radio buttons and textareas in the container div and remove the last one


$('#minus').click(function(){
    var textareas = $('#container textarea');
    var radiobtns = $('#container input');

    if (textareas.length > 1) {
        textareas.last().remove();
        radiobtns.last().remove();
        i--;
    }
});

Therefore to sum up, the jQuery code will look like this (don’t forget to include the jQuery file)


$(document).ready(function(){
    i=2;
    $('#plus').click(function(){
        $('#container').append('<div style="float:left; margin-right:10px;"><input type="radio"></div><textarea placeholder="TextBox '+i+'"
rows="2"></textarea><div style="clear:both;"></div></div>');
        i++;
});

    $('#minus').click(function(){
        var textareas = $('#container textarea');
        var radiobtns = $('#container input');

        if (textareas.length > 1) {
            textareas.last().remove();
            radiobtns.last().remove();
            i--;
        }
    });
});

Leave a Reply

Your email address will not be published.