RuiVBoas RuiVBoas - 3 years ago 96
Javascript Question

Prevent reload page with code added afterwards and after clicking a button

first of all I'm trying to create a form where is needed to duplicate some blocks of fields and fields as the user want.

So I have a page where there is a button that after clicking on it duplicates a certain block. The first button works fine!, it duplicates a block without reloading the page when is clicked.

But in that block there are some input fields that I need to duplicate as well.

So when the block is duplicated a new button is added to duplicate fields inside that block.

The problem is that when I click on the second button it reloads the page, instead of just duplicate an input field.

To do this I'm using jquery, code to duplicate the block, this is the code to add the block, that is working fine:


$('#add-block').click(function(e) {
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
event.preventDefault();
});


code to duplicate the field (here is where the page reloads):

$('#we2_add_test').click(function(e) {
event.preventDefault();
$(".we2_test-input").append("<input type=\"text\" placeholder=\"Your Test\" class=\"form-control\" name=\"we3_test\" id=\"we3_test\">");
return false;
});


I already tried this, but it didn't work

Answer Source

1.id="we2_test" need to be class="we2_test" and id=we2_add_test need to be class="we2_add_test",because multiple same id for different HTML element is wrong when you are going to deal them with jQuery

2.Use event delegation:-

Now both code need to be:-

$('#add-block').click(function(e) {
    e.preventDefault();
    var html_to_add = '<input type="text" placeholder="Your Test we2_test" class="form-control" name="we2_test">';
    html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
    html_to_add += '<button class="btn btn-default btn-add-test we2_add_test">+</button>';
    $(".block-input").append(html_to_add);

});
$(document).on('click','.we2_add_test',function(e) {
    e.preventDefault();
    $(".we2_test-input").append("<input type='text' placeholder='Your Test' class='form-control we3_test' name='we3_test'>");
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download