Search code examples
jqueryhtmlonclickpreventdefault

preventDefault not working when multiple buttons with the same class


I have a button that appends some form elements to a div. The thing is, the button is duplicated on append as well. On first click of "add" button, another row of form elements is added. When I click on the "add" button that was added from first click (to add another row), the page refreshes (preventDefault is not working). The remove button works, but I am stuck only able to add a single row. I'd like to have the "add" button on each row, but not sure how to accomplish this.

Here's the code:

<form class="form-inline" role="form">
    <div class="butter">
        <div class="form-group">
            <label class="sr-only" for="exampleInputEmail2">Email</label>
            <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email">
        </div>
        <div class="form-group">
            <label class="sr-only" for="exampleInputPassword2">Password</label>
            <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password">
        </div>
        <button class="btn btn-info nutter">add</button>
    </div>
</form>

<script id="add_form">
    <div class="spacer">
        <div class="form-group">
            <label class="sr-only" for="exampleInputEmail2">Email</label>
            <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email">
        </div>
        <div class="form-group">
            <label class="sr-only" for="exampleInputPassword2">Password</label>
            <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password">
        </div>
        <button class="btn btn-info nutter">add</button>
        <button class="btn btn-danger gutter">remove</button>
    </div>
</script>

$(document).ready(function() {
    var wrapper         = $('.butter'); //Fields wrapper
    var add_button      = $('.nutter'); //Add button ID

    $(add_button).click(function( e ) { //on add input button click
        e.preventDefault();
        var text = $('#add_form').html();
        $(wrapper).append(text); //add input box
    });

    $(wrapper).on("click",".gutter", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

Here's the jsfiddle: http://jsfiddle.net/7o1rgsw3/1


Solution

  • Since you are adding html dynamically with each click you need to use the on method instead of click

    $(document).ready(function() {
        $(document).on('click', '.nutter',function(e) { 
            e.preventDefault();
            var text = $('#add_form').html();
            $('.butter').append(text);
        });
    
         $(document).on("click",".gutter", function(e){ //user click on remove text
            e.preventDefault(); 
            $(e.target).closest('.spacer').remove();
        });
    });
    

    and here is the fiddle