Dynamically insert a new bootstrap 4 card

Does anyone know how to dynamically add a new card using JavaScript? The code provided allows for the removal of a card, but not the addition of a new one.

I attempted to start something like this, but I am currently stuck.

An example of the HTML code:

The card

<div class="container">
    <div class="row">
        <button type="button" class="btn btn-primary" aria-label="Insert" onClick="addAnother()" id="insert">
            <span aria-hidden="true">Insert</span>
        </button>
    </div>
     <div class="row"> 
        <ul class="row list-unstyled" id="list">
            <li class="col-md-4" id="element1">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">Card title <a class="close" href="#">×</a></h4>
                        <p class="card-text">Some example text. Some example text.</p>
                        <a href="#" class="card-link">Card link</a>
                        <a href="#" class="card-link">Another link</a>
                    </div>
                </div>
            </li>
            <li class="col-md-4" id="element2">
            <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">Card title <a class="close" href="#">×</a></h4>
                        <p class="card-text">Some example text. Some example text.</p>
                        <a href="#" class="card-link">Card link</a>
                        <a href="#" class="card-link">Another link</a>
                    </div>
                </div>
            </li>
            <li class="col-md-4" id="element1">                
            <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">Card title <a class="close" href="#">×</a></h4>
                        <p class="card-text">Some example text. Some example text.</p>
                        <a href="#" class="card-link">Card link</a>
                        <a href="#" class="card-link">Another link</a>
                    </div>
                </div>
            </li>
         </ul>
      </div>
 </div>
</body>

The script for removing a card:

Remove a card

<script type="text/javascript">
    $('.close').click(function(){
    var $target = $(this).parents('li');
    $target.hide('slow', function(){ $target.remove(); });
    })

</script>

Add a card ==> This element is not correct, it must include the card code instead, I believe

<script>
    addAnother = function() {
        var ul = document.getElementById("list");
        var li = document.createElement("li");
        var children = ul.children.length + 1
        li.setAttribute("id", "element"+children)
        li.appendChild(document.createTextNode("Element "+children));
        ul.appendChild(li)
    }
</script>

Answer №1

To add a click event, you can use the id #insert just like how you did for the close action, instead of directly mentioning a function within the code.

 $('#insert').click(function(){

     $( "ul#list" ).append( "<li>add your HTML content here</li>" );

});

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

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

Modifying webpage code

I am looking to develop a system where I can edit various elements such as the navbar, paragraphs, and images directly from a web page. I understand that this can be achieved with JavaScript, but I am facing the issue of my customizations reverting to defa ...

Inquiring about Vue component prop defaults and detecting when a user has not assigned a value

1. I am looking for a way to set a default value for a component prop in Vue 2. Take, for example, a basic movies component that can be utilized like this: <movies year="2016"><movies> Vue.component('movies', { props: ['yea ...

Place the React rendering inside a class element, rather than an ID

For my project, I need to display the same information in multiple locations using react. Instead of targeting elements by id (as shown in the code below), I would like to use class selectors. ReactDOM.render(<App />, document.getElementById('a ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

What is preventing the function from successfully compiling text from various files that are uploaded using the HTML5 file reader into an array?

My current challenge involves attempting to upload two text files using the HTML 5 file reader. While I can successfully get the files into an array, encountering difficulty arises when trying to return that array from the function. One solution could be ...

Tips for using regular expressions with the find method in JavaScript?

Welcome to my Object: let data = [{ "title": "User info", "category": "personal", "userId": "abc12345" }, { "title": "Customer Info", "category": ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

Tips for increasing the number of inputs within a form using <script> elements

I am currently working on a form within the script tags and I would like to include additional input fields before submitting. However, the submit button seems to be malfunctioning and I suspect that there may be an issue with how I am accessing it in my c ...

Adding the location of the onClick event to the hook - a step-by-step guide

Here is the code I am working with: import { MapContainer, TileLayer } from "react-leaflet"; import React, { useState } from 'react'; export default function App() { const [positionLat, setPositionLat] = useState(null); ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...

What methods can I employ JSON to create a dynamic Sidebar within Nextjs?

[ { "type": "root", "children": [ { "type": "file", "route": "Open-EdTech/AWS-Associate-Notes/EC2.md", "title": "EC2", ...

The sticky element should only be active when the visible section is overflowing vertically. There should be no scrollbar if the height is minimal

I'm currently working on a Whatsapp-style navigation bar and facing an issue with the sticky navbar functionality. https://i.stack.imgur.com/Cy3lA.gif Please refer to the details below for more information. To resolve this issue, I have included ...

What is the best method for dividing a user interface into several arrays of keys, each grouped by type?

Given a simple structure: structure IPerson { firstName: string; lastName: string; age: number; city: string; favoriteNumber: number; isMarried: boolean; hasDriverLicense: boolean; } How do I create arrays containing keys grouped by data typ ...

Is there a way to access a variable declared in index.js from a controller?

Currently, I am experimenting with forms-angular (). In my index.js file, I have defined a variable called DataFormHandler. However, I am facing an issue trying to access this variable in my controllers. The setter app.set("formHandler", DataFormHandler) ...

What is the process for sending an image as input to a Django view using an Angular frontend?

I currently have a django web api with an angular frontend that allows users to upload and view images. My goal now is to expand this functionality: when the user clicks the "segment" button (see image), it should send the corresponding image to my python ...

Issue with VueJs and ChartJs not displaying custom options when making an API call

Having trouble populating my chart with data from the API. Despite setting extraOptions for my chart, it defaults to default options when rendered. Here is the component code: import { Bar, mixins } from 'vue-chartjs'; export default { name: ...

Tips on editing a file exclusively when a specific requirement is fulfilled

Looking for a way to implement a put method within an Express API that allows users to update a document conditionally? Consider this scenario: you have an Instance document with an attribute called executed, which is set to true if the instance has been e ...

Executing a command to modify the local storage (no need for an API request) using redux persist in a React Native environment

Currently, I am facing an issue where I am attempting to trigger an action in Redux sagas to assign an ID to a local store: import { call, takeEvery } from 'redux-saga/effects'; import { BENEFITS } from '../actions/types'; function* ...

When the div is refreshed, the input box should retain the text instead of clearing it

I am facing an issue with a div that refreshes every 3 seconds. There is an input box inside the div, but whatever I type gets cleared out in 3 seconds. Is there a way to prevent the text from being cleared out and keep it inside the input box? index.js ...