Reputation: 103
Please help to adjust the code:
$('parent').click(function(){
$(this).html('<button> child <button/>');
$('button').click(function(){
$(this).parent().html('some new html');
});
});
I am trying to create the dynamic action conformation with jQuery. For example user clicks DELETE (parent). DELETE then is changed to YES / NO (child button). User clicks NO and parent html is becoming DELETE again.
Upvotes: 0
Views: 213
Reputation: 8246
Why can't you use the JavaScript confirm popup box? That way you don't need to edit the DOM at all and lives are made easier :).
$('parent').click(function(){
var blnDelete = confirm("Do you want to delete?");
if (blnDelete) {
// Delete
} else {
// Don't Delete
}
});
http://www.w3schools.com/jsref/met_win_confirm.asp
Upvotes: 0
Reputation: 3047
You could create a new jQuery element and then append this, you can then assign the click handler to only that element.
$('#parent').click(function(){
var yesBtn = $('<button type="button">Yes</button>');
var noBtn = $('<button type="button">No</button>');
$(this).html('');
$(this).append(yesBtn);
$(this).append(noBtn);
$(yesBtn).click(function(){
event.stopPropagation();
// On yes event handler
$(this).parent().html('You clicked Yes!');
});
$(noBtn).click(function(){
event.stopPropagation();
// On no event handler
$(this).parent().html('You clicked No!');
});
});
Not the event.stopPropagation();
in the child click handlers, this will stop the event bubbling up the DOM tree and re-executing the initial parent
click.
Upvotes: 0
Reputation: 388316
You can try delegated event handlers like
$(document).on('click', '.delete', function () {
$(this).replaceWith($('<span />', {
html: '<button class="yes">Yes</button><button class="no">No</button>'
}))
})
$(document).on('click', '.no', function () {
$(this).parent().replaceWith($('<button />', {
text: 'Delete',
'class': 'delete'
}))
})
$(document).on('click', '.yes', function () {
console.log('delete')
})
Demo: Fiddle
Upvotes: 1