s.k.paul s.k.paul - 3 months ago 8
jQuery Question

Dynamically add textbox(s) in jquery

I have the following code-

<div class="service_box">
<div class="form">
<form class="cmxform">
<label>EL POS :</label>
<input type="checkbox">
<!-----------------------
multiple textboxes shall be added here as
<input type="text" class="someclass"> ---> textbox 1
<input type="text" class="someclass"> ---> textbox 2
------------------------>
<button id="add">Add</button>
</form>
</div>
</div>


I would like to add textbox(s) on the add button click event in jquery. Any help?

Answer

The following code will enable you to both add text boxes and remove them, just in case you change your mind:

$(function() {
    $('#add').on('click', function( e ) {
        e.preventDefault();
        $('<div/>').addClass( 'new-text-div' )
        .html( $('<input type="textbox"/>').addClass( 'someclass' ) )
        .append( $('<button/>').addClass( 'remove' ).text( 'Remove' ) )
        .insertBefore( this );
    });
    $(document).on('click', 'button.remove', function( e ) {
        e.preventDefault();
        $(this).closest( 'div.new-text-div' ).remove();
    });
});

JS FIDDLE DEMO

Comments