Avoid removing all subsequent div elements when using parent() in jQuery -
i have tried using closest() , parent() jquery methods both seem delete of divs following 1 trying remove . not wish assign id each new div dynamically generated
$(document).ready(function() { $(document).on('click', '.add_row', function() { alert("add new row method called"); $(".student_mounting").last().append('<div class="student_mounting">' + '<button class="add_row" src="../images/add-resource.png">add</button>' + '<button class="remove_row" src="../images/exit.png">remove</button>' + '</div>'); }); $(document).on('click', '.remove_row', function() { $(this).closest().remove(); }); });
.student_mounting { position: relative; top: 12px; height: 120px; width: 265px; border-radius: 6px; margin-top: 120px; background-color: #f4ebbc; z-index: 4; border: 2px solid #6b4235; border-radius: 5px; color: black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <div class="student_mounting"> <button class="add_row" src="../images/add-resource.png">add</button> <button class="remove_row" src="../images/exit.png">remove</button> </div>
here add parent div having id 'studentparent' , add dynamically created div inside parent div. work when remove div using parent() function.
when execute code can identify div removed when press remove button.
$(document).ready(function() { $(document).on('click' ,'.add_row', function() { alert("add new row method called"); var value=$("#hidval").val(); value++; $("#hidval").val(value); $("#studentparent" ).last().append('<div class="student_mounting">'+ '<button class="add_row" src="../images/add-resource.png">add '+value+'</button>'+ '<button class="remove_row" src="../images/exit.png">remove</button>'+ '</div>'); }); $(document).on('click' ,'.remove_row', function() { $(this).parent().remove(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style> .student_mounting { position:relative; top:12px; height:120px; width:265px; border-radius:6px; margin-top:120px; background-color:#f4ebbc; z-index:4; border: 2px solid #6b4235; border-radius: 5px; color: black; } </style> <div id="studentparent"> <input type="hidden" id="hidval" value="1"> <div class="student_mounting"> <button class="add_row" src="../images/add-resource.png">add 1</button> <button class="remove_row" src="../images/exit.png">remove</button> </div> </div>
Comments
Post a Comment