Creating objects in real-time with the simple click of a button

I am attempting to design a layout with 2 rows of 6 rectangles grouped as one element.

In addition, I wish to include a plus button that will reveal a new set of rectangles above or below the original ones when clicked. The placement of the new set will depend on which plus button is clicked.

My goal is to achieve the following:

https://i.sstatic.net/P26sC.png What I have experimented with/discovered so far:

$(function () {
    $(".repeat").on('click', function (e) {
        e.preventDefault();
        var $self = $(this);
        $self.before($self.prev('table').clone());
        //$self.remove();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
    <div class="repeatable">
        <table border="1">
            <tr>
                <td>
                    <input type="text" name="userInput[]" />
                </td>
            </tr>
        </table>
        <button class="repeat">Add Another</button>
    </div>
    <input type="submit" value="Submit" />
</form>

The provided example only functions for forms. Does anyone have suggestions on how I can adapt this for my specific requirements?

Answer №1

I have made adjustments to your code to enable adding elements either on top or below.

The event listener has been modified to check if the button has a specific class, allowing for placement above or below. It now also listens to clicks on the "body", ensuring that new DOM elements without attached event listeners are accounted for:

$("body").on('click', ".repeat", function (e) { //additional code here}

Furthermore, I have updated the HTML structure so that it is not reliant on a specific "form" element, making it possible to change the element types as long as the classes are preserved.

$(function () {
    $("body").on('click', ".repeat", function (e) {
        e.preventDefault();
        var $self = $(this);
        var $parent = $self.parent();
        if($self.hasClass("add-bottom")){
          $parent.after($parent.clone());
        } else {
          $parent.before($parent.clone());
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  
  <div class="container">
    <div class="repeatable">
      <button class="repeat add-top">Add above</button>
        <table border="1">
            <tr>
                <td>
                    <input type="text" name="userInput[]" />
                </td>
            </tr>
        </table>
        <button class="repeat add-bottom">Add below</button>
    </div>
  </div>

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

Featuring my Cookie page prominently on my website's homepage

I am facing a simple issue: I have a cookie verification page (cookies_check.php) that I want to include on my home page (accueil.php). So, currently, the only code on accueil.php is: <?php include ('Controleur/cookies_check.php'); ?> He ...

Turkish text is not appearing correctly on the UIWebview when embedded in HTML

One of the challenges I encountered in my iOS project involved programming a UIWebView to load content in both English and Turkish from a web service. To accomplish this, I formatted the HTML string with the necessary headers and saved it locally before pr ...

Is there a simple way to create a row of triangle-shaped divs using Bootstrap, similar to the design shown

Is it possible to have a white section and background image in the same row? I am aiming for a layout similar to the example shown https://i.stack.imgur.com/J0S2t.jpg ...

Transmitting information from Angular to Laravel

Hey, I'm facing a challenge once again. Currently, I am working on creating a to-do list application using Laravel and Angular. While I can successfully retrieve data from the database through the Laravel and Angular controllers, I'm encountering ...

Transforming data in javascript

I am faced with a data transformation challenge involving extracting information from user input in Apache Superset using metrics. The data is assigned to the variable dataTransformation. {country: "Afghanistan", region: "South Asia", y ...

Achieving the perfect button using a combination of material-ui and styled-components

Utilizing the ToggleButton and ToggleButtonGroup components from material-ui, starting with material-ui's gatsby template. To prevent common material-ui errors with production builds, I am attempting to incorporate styled-components as well. The foll ...

How to effectively send data from jQuery to PHP

I've been trying to figure out how to pass a value from jQuery to PHP. I've come across similar codes, but none of them seem to work for me. Every time I use alert, it shows the value of the variable, but when I open the site, there is nothing th ...

I am looking to preload a separate webpage prior to the HTML loading in AngularJS

I am looking to implement a feature in my AngularJS app where a different webpage (e.g. google.com) will be loaded based on the response of a REST API before any default HTML content is displayed. I have attempted to make a REST service call within a fact ...

How can I create a semantic-ui dropdown with a dynamically generated header?

Here are the dropdown options: const options = [ { key: '1', text: 'Example 1', value: 'Example 1', type:'ABC' }, { key: '2', text: 'Example 2', value: 'Example 2', t ...

Node.js Express post query failing to set content type

I have a POST request implemented with the express framework to submit a query to a rest api. Here is the relevant code snippet: var request = require('request'); app.post('/compute', function(req, postResponse) { var queryJSON = re ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

ReactJs - Organize your data with the sort method

In my React application, I have a table that fetches its data from an API. I need to implement sorting for one of the columns. The values in this column are usually strings of numbers but sometimes can be equal to "-" (Dash). Below is the sort function I ...

Utilizing Google Maps API to dynamically input destinations in text boxes

Check out my code at this link: I apologize for the inconvenience, but I had some difficulty pasting it directly into this forum. The code is functioning well, however, I need assistance with a particular issue. Currently, the textboxes for start and des ...

What is the best way to centralize the storage of my website's header and footer?

Constantly updating headers and footers requires me to manually transfer the code to each web page every time, which is not the most efficient method. I'm considering using a "header" and "footer" div, and using jQuery's $(document).ready functio ...

I need a counter in my React application that is triggered only once when the page scrolls to a specific element

I've encountered a challenge with a scroll-triggered counter on a specific part of the page. I'm seeking a solution using React or pure JavaScript, as opposed to jQuery. Although I initially implemented it with states and React hooks, I've ...

Issue with updating dropdown values in real-time in React

I am a beginner with React and I have a question regarding fetching dropdown values from the backend. Despite using async-await functions, the list is not getting populated with items. Any assistance in this matter would be greatly appreciated. Here is th ...

Printing SQL output from console.log into HTML with rows and columns can be achieved by following these steps

Here is the sample HTML code I have, which prints the data in a proper table format: redshiftClient.query('SELECT top 10 * FROM table') .then(function (data) { console.log(data); var mail = { from: '******@ou ...

Need help with checking for the presence of a value in a multidimensional array using Node.js/Javascript?

Imagine you have an array structured like this: $game = Array ( ['round'] => Array ( ['match'] => Array ( ['player_2'] => Array ( ...

Is your overlaying div functioning properly in Chrome and Firefox, but encountering issues in Internet Explorer?

I am facing a challenge with overlaying two divs on top of an image. My objective is to create a simple lightbox where when the user hovers over the left or right side, the cursor changes to a pointer and arrows appear. Below is the code I am using: HTML: ...

What mechanisms do chat apps use to detect when a user sends a message and trigger a re-render of the chat

Do I need to implement websockets for my React chat app using MySQL? I'm facing an issue where the app doesn't re-render when I open it in a new tab and type a message. Should I consider using websockets for real-time updates, or are there any ot ...