I'm new to jQuery and struggling with the .remove()
method. Despite finding similar questions, I'm still unable to solve my issue.
Within an HTML file, there's a form alongside a div
acting as an alert box, indicating whether the form was validated successfully. Initially, this div
contains a button for closing it:
<div id="my-form-alert-box">
<button id="my-form-alert-button" type="button" class="close">x</button>
</div>
On page load, the alert box should be hidden. To achieve this, I use the following CSS:
<style type="text/css">
#my-form-alert-box {display: none;}
</style>
After submitting and validating the form, I append <p>some text</p>
inside the div
, causing the alert box to appear. However, when I close the alert box by clicking the button, the text remains visible. Why is that?
Below is the jQuery code I've implemented:
$(document).ready(function() {
var $myFormAlertBox = $('#my-form-alert-box');
var $myFormAlertBoxParagraph = $('#my-form-alert-box p');
$('#my-form-alert-button').on('click', function(event) {
$myFormAlertBoxParagraph.remove();
$myFormAlertBox.hide();
});
$('#my-form').on('submit', function(event) {
$.ajax({
// ...
success: function(data) {
$myFormAlertBoxParagraph.remove();
$myFormAlertBox.hide();
$myFormAlertBox.append(data).show();
}
});
event.preventDefault();
});
});
The data appending works correctly, but the removal does not. Any assistance would be greatly appreciated! Thank you!