What is the best way to avoid adding duplicate HTML content to Bootstrap modal divs using jQuery?

In my project, I wanted to create a functionality where clicking on an image would trigger a modal box to pop up with additional content added once. However, I encountered two issues that I'm currently facing. Firstly, the header text that I intended to append does not seem to be appending to the header element as expected. Secondly, every time I click on the laptop image, the same paragraph keeps getting appended to the modal box repeatedly.

Below is a snippet of the HTML and JavaScript code I used:

<!--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>

The JavaScript part included a script to open and close the modal box when clicking the image or the close button:

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');
});

If you need further clarification or details, feel free to check out my JSFiddle here.

I've been struggling to find a solution for temporarily removing the paragraph when closing the box. I attempted using .remove(), but it ended up completely removing the paragraph every time the laptop is clicked. The use of .detach() didn't work out as expected either.

Answer №1

If my interpretation of the desired functionality is accurate, then it seems like you need to use .empty()

When closing the modal, consider including this snippet:

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

Answer №2

Modify the modal box onclick function as follows:

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

The 'empty' function should be included in the open modal to prevent adding additional paragraphs when clicking on an already opened modal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HtmlUnit - Issue encountered while handling Ajax requests with jQuery

I have been using htmlUnit to process a large amount of content for divs through Ajax on a certain page. Despite trying everything, I am unable to get the updated page with the changes after clicking the button. It appears that the code inside the script b ...

Harnessing PHP-grown JSON to retrieve information using JQuery

After successfully using Alert on the response parameter in jQuery, I can see the values I need. However, the issue arises when trying to extract them using key/value pairs. I'm not sure if this is a compatibility problem with the JSON format from PHP ...

Filtering options in a dropdown box with jQuery

I have implemented a feature where the content of one select box is filtered based on the option selected in another select box. Below is the code snippet that achieves this functionality: // Filter content based on the selected option in a region select ...

Tips for creating a tabbed form that easily glides between tabs

After coming across this form design, I am inspired to create something similar with a twist. Instead of having each tab display all content at once, I want the tabs to scroll from right to left, giving it a more animated effect. Can someone offer suggesti ...

there is no minimum height specified for the table

Hey there! I'm working on a dynamic table that I populate using data from my API. However, I'm facing an issue where I want the table to maintain a minimum height when there are only a few results, but I can't seem to make it work. I attemp ...

Ways to update a div periodically with new data fetched from a file - Here's How!

I am looking to auto-refresh a specific div every few seconds on my index.php page below. <?php session_start(); if (! check_write()) { redirect('testlogin.php'); return; } if (file_exists('lmt.json')) { $lmt = json_de ...

How can I create my own unique scrolling behavior in JavaScript?

Looking to create a similar effect as seen on this website: where the vertical scrollbar determines the movement of the browser "viewport" along a set path. I believe that using Javascript to track the scroll bar value and adjust background elements acco ...

The function "Jest spyOn" does not exist

I’m currently facing an unfamiliar error while testing my React component using Jest. Here’s the code snippet for my <Row/> component: In my Row component, there are various methods like showDetailsPanel(), handleStatusChange(), handleModalCanc ...

Retrieve information from API by making an AJAX request utilizing a variable

I need help figuring out how to correctly output a list of field names using an AJAX call. The desired output should be similar to var test = ['test1', 'test2', etc.] JQuery: var test = [ $.ajax({ type: 'GET', ...

When using jQuery to parse JSON, I am unable to make changes to an array

inventory = new Array(); $.getJSON('items.php', function(data){ $.each(data , function(i,jsonData) { inventory[1] = "item"; }); }); alert(inventory[1]); This code is supposed to display the items in the inventory, but it's ...

Is there a way to implement this code to filter every column in the grid?

I have been using this code in my grid view, but it only filters one column of the grid. Now I want to modify the code to filter multiple columns. I tried implementing a loop, but it seems like the code is not working correctly. Is there a way to adjust t ...

Update the database with the new values and display them in an HTML table

I am working with a table that looks like the one below: <script> $("#edit").hide(); // Initially hide the edit table $("#update").click(function() { $("#edit").toggle(); $("#shown").toggle(); ...

Converting Callbacks to Promises in Node.js

I am facing a challenge with my node js application as I am attempting to promisify multiple callback functions without success. It has reached a point where I am unsure if it is even feasible. If you can assist me in promisifying the code provided below, ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

I am experiencing an issue where my React component fails to update properly when viewed in Safari

Everything seemed to be going smoothly. Functioning perfectly in Chrome, FF, Edge, and even IE 11! The main component holds all the state. I send the bets object to the child component which calculates a count to pass to the grandchild component for displ ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

Is there a way to prevent tinymce from automatically inserting <!DOCTYPE html><html><head></head><body> before all my content?

I have integrated TinyMCE as the editor for one of my database fields. The issue I am encountering is that when I input the text "abc" into the editor, it gets saved in the database surrounded by unnecessary HTML elements. This is the structure currently s ...

Removing special characters in ASP

Can someone please advise me on how to remove special characters in ASP (classic)? I am using an MS Access database. Is there a function similar to stripslashes() or addslashes() in PHP that can help with this? Any assistance would be greatly appreciated ...

Tips for positioning a div element within the body of a webpage to maintain a predetermined height and width

Currently, I am developing a single-page application using AngularJS. I have specific routes in mind where I want to introduce new HTML templates. To accomplish this, I have created a container labeled with the ID #main positioned between two navbars (he ...

Top method for showcasing only unique values from various div tags with identical class names

Is there a way to show only unique values from multiple divs with the same class name? <div class="categories">cat 1</div> <div class="categories">cat 1</div> <div class="categories">cat 2</div> <div class="categorie ...