as1216 as1216 - 3 months ago 6
CSS Question

How do you prevent appending html multiple times in BS modal divs in jQuery?

Whenever I click on an image, a modal box should pop up with an appended paragraph once. I have two issues. Firstly, my header text doesn't append to the header element. Secondly, it keeps appending the same paragraph into the modal box every time I click the laptop.

HTML

<!--Trigger Image -->
<img src="https://cdn2.iconfinder.com/data/icons/pittogrammi/142/02-512.png" id="laptop" class="openmodal">

<!--Modal Box -->
<div class="question" id="question-modal">
<header id="modal-header">
<a href="#" class="close">X</a>
</header>
<div class="answer">
</div>
</div>


JS

var id = this.id;

//Open the modal box
$('.openmodal').on('click', function() {
$('#question-modal').modal('show');
if (id == 'laptop')
$('header').append('<h3>FAQs on laptops</h3>');
$('.answer').append("Mac > any PC");
});

//close modal box
$('.close').on('click', function() {
$('#question-modal').modal('hide');
});


Here's my JSFiddle if that description wasn't clear.

I'm not sure as how to temporarily remove the paragraph when you close the box. I tried .remove() but when the laptop is clicked, the paragraph is removed completely (well no duh). .detach() doesn't work either.

Answer

If I'm understanding the desired behavior correctly, then I believe you are looking for .empty()

In your close modal callback, try adding:

$('.answer').empty();