JamesF
JamesF

Reputation: 67

Issues deleting dynamically created Divs using JQuery

I have a button which deletes the div it is contained in. The divs are created dynamically using Jquery, I am using this to delete each div:

$('.shift_button').click(function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

However, nothing happens when the button is pressed, the div remains. Any idea what I'm doing wrong?

Here is how the div is created:

$('#shifts_to_complete').append('<div id="'+ length +'" class="current_shift" data-role="fieldcontain"></div>');  
$('#'+ length +'').html('Location: ' + obj.shift_location + '<br>Date: ' + obj.shift_date + '<br>Shift Starts: ' + obj.start_time + '<br>Shift Ends: ' + obj.end_time + '<br>Hours Worked: ' + obj.duration + '<br>Pay for Shift: &pound' + shift_pay + '<br><button class="shift_button ui-btn ui-shadow ui-btn-corner-all ui-btn-up-b" id="btn_'+ length +'">Completed?</button>');

Thanks

Upvotes: 2

Views: 560

Answers (1)

A.T.
A.T.

Reputation: 26332

use event delegation :

$(document).on('click','.shift_button',function(e) 
{ 
 e.preventDefault(); 
  $(this).parent().remove(); 
});

it will bind events to all future dynamic elements of document, as document is the parent element which always exists.

Upvotes: 2

Related Questions