Second append doesn't work on jquery

367 views Asked by At

I have a form and need to append a field as many times as required. If the button CLICK TO ADD ANOTHER FIELD is clicked the div should be appended. After the first append (onload), the div responses correctly but from the second one on, I am not getting the similar response from the div. Here is my JSFiddle

If I click on the TEST BUTTON , I get alert for the first div but on adding another div (by clicking the CLICK TO ADD ANOTHER FIELD button) , the button (TEST) doesn't work anymore for the second div onwards.

I tried clone() to help this but unable solve this one. May be I am not using it correctly.

To replicate the issue please follow the steps::

  • Click on the CLICK TO ADD ANOTHER FIELD button to add div
  • Click on the TEST button on the second div onwards

Please take a look and suggest. Thanks in advance.

3

There are 3 answers

0
Akshay On BEST ANSWER

You have to use delegation like $(document).on('click','.test',function(){

var count = 1;
 
$.fn.addclients = function(add){
 
var mydiv = '';

mydiv = '<div class="dataadd"><fieldset><legend>Test: '+add+'</legend><b>Test Name :</b> <input type="text" id="ct'+add+'" name="cname" value="" style="width:250px" />'+
            ' <button class="test" id="test" style="float:left;">TEST</button>'+
'<br>'+
'</fieldset></div>';
//$(".dataadd").clone().appendTo('#registerForm');
      
$('#registerForm').append(mydiv);
}
$.fn.addclients(count);

$(document).on('click','#btn',function(){
  ++count;
  $.fn.addclients(count);
        return false;
});

$(document).on('click','.test',function(){
  alert("test");
    return false;
});
.zend_form{
   font-weight:bold;
 font-size:10px;
 width:358px; 
    float: left;
    
}
.dataadd{
 font-weight:bold;
 font-size:10px;
 width:358px;
 //border: 1px solid;
 margin-top: 15px;
 margin-bottom: 15px;
 //padding: 5px;
 //float:left;
}
.selectbox{
 margin-top: 15px;
 width:155px; 
 height:100px;
}
.buttonc{
 background-color: #fff;
 width:145px; 
 height:45px;
}
.selection_area{
 font-weight:bold;
 font-size:10px;
}
input {
 width: 200px;
}

dt {
 width:50%; /* adjust the width; make sure the total of both is 100% */
 
}
dd {
 width:80%; /* adjust the width; make sure the total of both is 100% */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="registerForm" enctype="application/x-www-form-urlencoded" method="post" action=""><dl class="zend_form">
<dt id="firstname-label"><label for="firstname" class="required">First Name:</label></dt>
<dd id="firstname-element">
<input type="text" name="firstname" id="firstname" value="" style="width:200px; float:left;" /></dd>
<dt id="middlename-label"><label for="middlename" class="optional">Last Name</label></dt>
<dd id="middlename-element">
<input type="text" name="middlename" id="middlename" value="" style="width:200px" /></dd>
    </form>    
  <div style='display:table;background-color:#ccc;width:99%;padding:5px;'>
         <button class='buttonc' name='btn_sub' id='btn' style='float:left;'>CLICK TO ADD ANOTHER FIELD</button>
 </div>

0
monxas On

all elements created after body load must use delegation to work

$("body").on("click",".test",function(){
    alert("test");
    return false;
});

This way, the event is attached to the body, witch always exists, but only triggers when the matched elements appear, no matter when they're created (before or after js is loaded)

1
nathanvda On

You write:

$('#btn').click(function(){ ... });

but this will only bind the event handler to elements currently on the page when running this code. So elements added later will not be covered by this code.

But first tip: do not use a HTML ID (#btn) if you want to repeat it. So instead use a class (.btn), to capture all elements.

And then the best way is to write something like:

$(document).on('click', '.btn', function() { ... } ) 

This will capture any click event on the document (you could use a container div instead --just easier to show now), and only run the callback if it matches the given selector (.btn).