I’m currently doing my first steps in jQuery and have a problem with .remove(). There are already a lot of questions from people with similar problems but they don’t help me.
In a HTML file, I have a form and the following div that serves as an alert box and displays whether the form validated correctly or not. In its original state, the div contains a single button for closing it.
<div id="my-form-alert-box">
<button id="my-form-alert-button" type="button" class="close">x</button>
</div>
When the HTML page loads for the first time, the alert box should not be displayed. That’s why I add the following CSS:
<style type="text/css">
#my-form-alert-box {display: none;}
</style>
When the form gets submitted and validated, I append <p>some text</p> to this div and then the alert box is displayed. When I close the alert box using the button, it disappears but the <p>some text</p> is not removed. Why is this the case?
Here is my jQuery code:
$(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) {
// The content of the alert box should be removed
// and the alert box itself should be hidden also when
// the form gets submitted again and not only when the
// button is clicked
$myFormAlertBoxParagraph.remove();
$myFormAlertBox.hide();
// data contains <p>some text</p>
$myFormAlertBox.append(data).show();
}
});
event.preventDefault();
});
});
Appending the data works fine, but removing it does not. Can you help me? Thank you very much!
Your initial assignment of $myFormAlertBoxParagraph will fail as there isn’t a paragraph in your markup when it is called. Adding a ‘placeholder’ paragraph into your markup should fix it. This explains why the .remove() will fail.
For your ajax, try something like this to keep the variables assigned with their new values:
This will remove the paragraph tag from the alert box, and add the new one. There’s no need to .hide() it and then immediately .show() it afterwards. However, adding the .show() after the .append() will cover you if it has been hidden by your click event.