creating div elements dynamically using JavaScript

It is required that the user be able to dynamically add 5 divs by clicking on the plus icon. An alert should appear after attempting to add more than 5 divs, prohibiting any odd numbers from being added.

function addvv() {
  var numItems = $('div.box').length;
  if (numItems <= 5) {
    $('.box').clone().appendTo('.container');
    var x = document.getElementById("removediv");
    if (x.style.display === "none") {
      x.style.display = "block";
    }
  } else {
    alert('only 5 can be added');
  }
}

function removediv() {
  $(".box").remove();
}
<div class="container">

  <div class="box">

    <div style="background-color:blue;height: 26px;border-radius: 14px;">

      //this is the button to add divs dynamically

      <i class="fas fa-plus" id="adddiv" onclick="addvv()" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;"></i>
      <i class="fa fa-trash" id="removediv" onclick="removediv()" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;display:none"></i>
    </div>
    <div class="row" style="background-color:lightgray;height:100px;border-radius: 23px;">
      <div class="col-md-12" style="padding:10px">
        <div class="col-md-6">
          <label>Name:</label>
          <input type="text" id="name" />
        </div>
        <div class="col-md-6">
          <label>Salary:</label>
          <input type="text" id="salary" />
        </div>
      </div>
    </div>
  </div>
</div>

Please provide suggestions for a function to enable the addition of an odd number of divs as well. Thank you.

Answer №1

After reviewing your code, it appears that there were multiple issues identified. First and foremost, the conditional statement numLength <= 5 allows for the execution of the clone() function even when numLength == 5, resulting in a total of 6 clones instead of the intended 5. Secondly, the $('.box').clone() method will clone all elements matching the .box selector, leading to an incremental cloning behavior on each click.

To address these concerns, I have made adjustments to your code. The revised version ensures that only one clone is created at a time, displays #removediv on all but the first .box, and removes the corresponding .box element upon clicking on #removediv. Moreover, considering that IDs should be unique throughout the document, it would be advisable to utilize classes instead.

function addvv() {
    var numItems = document.getElementsByClassName('box');
    if (numItems.length < 5) {
        $('.box').first().clone().appendTo('.container');
        $('.box').not(':first').find('#removediv').css('display', 'block');
    }
    else {
        alert('Only 5 instances can be added');
    }
}

function removediv(e) {
    $(e).closest('.box').remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
    <div class="box">
        <div style="background-color:blue;height: 26px;border-radius: 14px;">
            <i class="fas fa-plus" id="adddiv" onclick="addvv()" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;">+</i>
            <i class="fa fa-trash" id="removediv" onclick="removediv(this)" style="color: red;float: right;margin-right: 15px;margin-top: 2px;font-size: 18px;display:none">-</i>
        </div>
        <div class="row" style="background-color:lightgray;height:100px;border-radius: 23px;">
            <div class="col-md-12" style="padding:10px">
                <div class="col-md-6">
                    <label>Name:</label>
                    <input type="text" id="name" />
                </div>
                <div class="col-md-6">
                    <label>Salary:</label>
                    <input type="text" id="salary" />
                </div>
            </div>
        </div>
    </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

Website automation can be simplified by utilizing the Webdriver.io pageObject pattern, which allows for element selectors

Currently, I am following a specific example to define elements within pageObjects using the ID selector... var Page = require('./page') var MyPage= Object.create(Page, { /** * defining elements */ firstName: { get: function ( ...

Issue with Context API rendering data array

I encountered an issue where I expected an assignment of a function call but instead saw an expression. After resolving the above error, I am now faced with an Unhandled Rejection (TypeError): render is not a function. Everything works fine until I navigat ...

How to execute a function *after* another function has finished running in Javascript upon page load?

I am currently using scrollsaver.js to maintain scroll positions of elements after postback. However, I have encountered difficulties in resetting the scroll position when needed. Specifically, when paging through a list, I want the scroll position to res ...

Help! The CSS height property is not working properly and I'm not sure how to resolve

I'm facing an issue with the height property of a specific div and I can't seem to fix it. SCSS: .security{ border: 3px #1D3176 solid; display: flex; h2{ position: ...

Perform stress tests on the Tapestry application utilizing JavaScript in conjunction with JMeter

I am currently attempting to load test a Tapestry application using JMeter. One challenge I have encountered is that the Tapestry app returns a response consisting mainly of JavaScript with no HTML to parse. In order to verify the response, I need to eva ...

Tips for managing the dimensions of the <label> element within a React component

I'm facing an issue where the element size is not matching the box size as expected. Additionally, the width property doesn't seem to work in React. Does anyone know how to solve this problem? const DragDrop = () => { ... return ( &l ...

transferring an array of objects in JavaScript to a servlet through jQuery's ajax method

Check out the array structure below: A[0] = { time, data[lon, lat], type } ... A[n] I need to transfer this array A to a servlet via jQuery ajax and ensure that I can access the same object on the servlet in order to retrieve values like A[0].data[0].la ...

Is there a way to set the z-index independent of its parent element's stacking order?

Struggling with creating a Netflix logo using only pure CSS. I have a span element and its before pseudo-element. The issue is figuring out how to position .netflix span:nth-child(2) in front on the z-axis compared to .netflix span:nth-child(2):before. Is ...

Which is more effective for transferring data between pages: HTML5 storage or Angular services?

I'm currently exploring ways to transfer data between two pages that have Angular controllers. So far, I've discovered two methods for passing data: through an Angular service (similar to the example found here) using HTML5 storage opti ...

Struggling to jest mock the useLocation hook in a React component that has been shallow mounted

Currently, I am working on testing a component that relies on the useLocation react hook. Despite my efforts to mock it, I keep encountering an error when trying to access useLocation().pathname because useLocation is undefined. Additionally, I have a que ...

Is there a way to verify the success of a Firebase push event upon submitting a form?

Here is the code for my polymer form and JavaScript. It works well in pushing data. What I would like to achieve is a way to verify if the push operation was successful or not. If it was successful, I want to hide the form and display a confirmation messag ...

The requested external js scripts could not be found and resulted in a net::ERR_ABORTED 404 error

import express, { Express, Request, Response } from 'express'; const path = require("path"); import dotenv from 'dotenv'; dotenv.config(); const PORT = process.env.PORT || 5000; const app = express(); app.use(express.static(path.join ...

Tips for utilizing a forward slash in route parameters

My GET REST service requires parameters containing slashes. The URL structure is as follows: "/term/:term/amount/:amount" where :term can include a string with slashes, such as "para/5MG". I am using express for my API and would like to avoid rewriting i ...

Error in Express JS: Attempting to access properties of an undefined variable (reading '0'). Issue with SQL query

Struggling to insert something in my database and then access it directly after. Due to the asynchronous nature of node.js, my plan doesn't seem to work out. However, I am confident that there is a solution to make this happen. Here's the code sn ...

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...

What is the best way to incorporate CSS conditions within a function?

After creating a filter function in React to organize images by category, I encountered an issue where the filtered images weren't centered as I wanted them to be. I am now looking for a way to integrate centering into the filtering process so that wh ...

Memory allocation and garbage collection in JavaScript anonymous functions

// Here is an Example of a Framework Method function sendAjaxRequest(uri, type , jsonData , callback){ var url : uri; $jq.ajax({ url: uri, type: type, data:jsonData , dataType: ResponseDataType.JSON, success: function(data){ ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

Effortlessly glide to a specific element on an HTML page

I am working with XML data that contains a lot of Test information. I am using XSLT to display this data as HTML in a web browser. Each test includes a table with the test steps, and every time a test is executed, the table updates to show whether each s ...

JavaScript throws an error because document is not defined

view image description hereWhy am I encountering an error after installing node.js and running various JavaScript commands? It seems like the issue is not with my code, but rather that node.js is failing to establish a connection with the server. view ima ...