jstandshigh
jstandshigh

Reputation: 109

Delete dynamically created dom elements on button click

I am creating a table pulling data from database, it is list of colleges and departments

 <div class="accord">
    <?php
       foreach($collegename as $clglist)
    { ?>

        <table class="table table-bordered">
            <thead class="head"><tr><th><h3><?php echo $clglist['college_name']; ?></h3></th>
                    <th><button id='clgname-<?php echo $clglist['college_id']; ?>'>delete</button></th></tr> </thead>
            <tbody>
            <?php

                    foreach($departmentname as $deptlist)
                    {

            ?>
            <tr><td> <?php
                          echo $deptlist['dept_name'].'<br>';
                      ?>
                        </td> <td> <button id='deptname-<?php echo $deptlist['dept_id']; ?>'>delete</button></td></tr>
                      <?php 
                   }
                ?>  
                </tbody>     
         </table>

       <?php        
    }
 ?>  
</div>

When the college name is clicked, the department names are displayed. I used jQuery for the toggle feature.

$(document).ready(function(){
jQuery(document).ready(function(){
    $('.accord .table .head').click(function() {
        $(this).next().toggle();
        return false;
    }).next().hide();
});

$("#clgname-<?php echo $clglist['college_id']; ?>").on("click", function() {
       alert("testing");
  });

I want to add delete feature so when the delete button is clicked beside the department name in each row that department row should be removed from the table. However nothing is happening when I click the button. I tried to create a alert message that also is failing. I am sure I am making some mistake, probably the id cannot be recognized for each button that I am assigning dynamically. Can anyone please look and tell me what to do here:

Upvotes: 1

Views: 371

Answers (4)

jstandshigh
jstandshigh

Reputation: 109

After spending some time reading about HTML Dom traversing. I finally found the answer to my question. I made some changes in the html.

 <div class="accord">
    <?php
       foreach($collegename as $clglist)
    { ?>

        <table class="table table-bordered">
            <thead class="head"><tr>
              <th><h3><?php echo $clglist['college_name']; ?></h3></th>
              <td><button value='<?php echo $clglist['college_id'];?>'>delete</button></td>
              </tr> </thead>
            <tbody>
            <?php

                    foreach($departmentname as $deptlist)
                    {

            ?>
            <tr><td> <?php
                          echo $deptlist['dept_name'].'<br>';
                      ?>
                        </td> 
                        <td> <button value='<?php echo $deptlist['dept_id']; ?>'>delete</button></td></tr>
                      <?php 
                   }
                ?>  
                </tbody>     
         </table>

       <?php        
    }
 ?>  
</div>

The first function deletes all the departments for the college, the second function deletes individual departments from each row. The last function is for toggle.

jQuery Solution:

$(document).ready(function() {

 $('table tbody').hide();

 $(document).on('click', '.accord .table .head tr td button', function(event){
      event.preventDefault();      
      var row = $(this).val();
      /*saved the college id to search & delete from database*/
      alert('College id is ' + row);    
     $(this).parent().parent().parent().next().remove();
});

 $(document).on('click', '.accord .table tbody tr td button', function(event){
      event.preventDefault();
      var row = $(this).val();
      /*saved the department id to search & delete from database*/
      alert('You clicked ' + row);
  $(this).parent().parent().remove();
});

 $(document).on('click', '.accord .table .head', function(event) {
        event.preventDefault();
        $(this).next().toggle();
    });  

});

Upvotes: 0

e-Learner
e-Learner

Reputation: 517

jQuery on function can attach events to non static elements before they have been loaded on DOM. Take a look in this code.

$(document).ready(function(){
	
	$('.table').on('click', '.toggle-departements, .delete-departement', function(theEvent){
		
		var whosTheGuilty = $(theEvent.currentTarget);
		if(whosTheGuilty.attr('class') == 'toggle-departements'){
			
			$('.fresh-departement').toggle();
			alert('toggled');
		}
		else if(whosTheGuilty.attr('class') == 'delete-departement'){
			$('.fresh-departement').hide();
			alert('hidden (You can also delete ;-)');
		}
		//.table is the static PARENT present when the page is loaded that you will attach your dynamic content event. And as you see, the click event is attached to .toggle-departements
		//And you can toggle now
   
		
		
	});
	
	//Content loaded after event 'click' declaration

	var dynContent = '<thead class="head"><tr><th><h3>Fresh College</h3></th><th><button class="toggle-departements">Toggle</button></th></tr></thead><tbody><tr class="fresh-departement"><td>Fresh Departement</td<td><button class="delete-departement" id="delete-fresh-college">Remove</button></td></tr></tbody>'
	
	$('table').append(dynContent);	
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accord">
	<table class="table table-bordered">
<!-- Empty Table content will Dynamically loaded here -->
	</table>
</div>

EDIT : As you requested; you can detect now the button who fired the event and delete etc...

Upvotes: 1

Yohanes Gultom
Yohanes Gultom

Reputation: 3842

Assuming there is only one button under head tag:

$('.accord .table .head button').on('click', function () {
    console.log('delete ' + this.id)
    $(this).parents('table').first().remove()
})

You can check the code live in https://jsfiddle.net/ks4ejz97/

If you have more than one button, I'd suggest using additional class eg: btn-delete

Upvotes: 1

idelara
idelara

Reputation: 1816

You need to use the following instead:

//$ is replaceable with jQuery
$(document).on('click', '.accord .table .head', function(){

//Do stuff here

});

This is the way you handle dynamically created DOM elements.

Upvotes: 1

Related Questions