Creating interactive web pages by dynamically adding div elements using JavaScript

I am attempting to incorporate HTML divs (with textfields) through a button click event. The structure of my form is as follows: When the add size button is clicked, it adds one row containing Price and size. Upon clicking the add More item button, I wish to append a new section with fields for name, price, and size, repeating this process. Here's a snippet of the HTML code:

<div class="clearfix"></div>
                    <div class="moreitems form-group" style="border:1px solid #ccc;height:200px;display:none;">

                     </div>

Below is my JavaScript code:

jQuery("#addmoreitems").click(function () {
    var options = jQuery("#select1").html();

    jQuery('.moreitems').css("display","block");
    var fld = '<div class="clearfix"></div><div class="form-group"><div class="col-sm-3"><label for="" class="text-left control-label">Product Name :</label></div><div class="col-sm-4"><input type="text" class="required-entry form-control" name="pname[]" id="pname"></div></div></div>';
   fld += '<div class="clearfix"></div><div class="form-group"><div class="col-sm-3"><label for="" class="text-left control-label">Price :</label></div><div class="col-sm-4"><input type="text" class="required-entry form-control" name="more_prices[]" id="prices"><select name="more_size[]" class="mysize">'+options+'</select></div></div>';
   fld += '<div class="col-sm-4"><div class="col-sm-3" style="margin-top:15px;"><button type="button" id="addsize" class="btn btn-info">Add Size</button></div></div>';
    
    jQuery('.moreitems').append(fld);
    jQuery('.mysize').html(options);

});

Currently, this code only adds elements on the first click. My goal is to have it add additional items each time the 'add more items' button is clicked. Additionally, when the 'add more size' button is clicked, I want to include fields for price and size.

Answer №1

The issue lies in the use of the html() function, which replaces all the html content every time you click the button. Instead, consider using the append() function to add HTML content without overwriting existing content.

Replace:

 jQuery('.moreitems').html(fld);

With:

 jQuery('.moreitems').append(fld);

Answer №2

Hey there, it seems like the issue may lie in how you are appending the HTML using the .html() method.

There is a notable difference between these two methods, and you can find more information about it in this reference link.

The main distinction is that .html() will overwrite the contents of the DIV, whereas .append() will simply add to the existing content. It's important to keep this in mind when working with your code. Additionally, make sure to properly bind the 'click' event by using both unbind and bind methods instead of just relying on 'click' alone. Here is an example:

$("#addmoreitems").unbind('click').bind('click',function () {
    
      // write your code here

});

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

Using HTML5 to overlay text on an image with a hyperlink

I'm interested in adding a hyperlink on top of an image using HTML5. Can you provide some guidance on how to achieve this? Regards, Ravi ...

Expanding a Zod object by merging it with a different object and selecting specific entries

Utilizing Zod, a TypeScript schema validation library, to validate objects within my application has led me to encounter a specific scenario. I find myself in need of validating an object with nested properties and extending it with another object while se ...

Utilizing Django framework for crafting a captivating homepage

Successfully set up the django framework and developed an app for my homepage. I added the app to the settings in the project folder and was able to get the HTML running smoothly. However, I am experiencing issues with styling as the CSS won't apply. ...

"Troubleshooting PHP Safari's Issue with Converting PDFs

I've been working on using headers and Imagick to display PDFs as images. Everything seems to be working fine in browsers other than Safari, where the image is displayed with a black background. You can check out an example here, along with the code u ...

Having issues with Drupal's lightframe and lightbox functionalities not functioning properly

I recently came across a Drupal 6 project that I have little knowledge about. My goal is to incorporate an Iframe into a lightbox, which seems simple but I'm encountering some obstacles. Despite researching online and attempting to implement the code ...

Is it considered the most appropriate method to implement a dynamic web page refresh by utilizing PHP, HTML, and AJAX in order to read a

My PHP page currently displays data from a database in tables, but the information is frequently changing. This means that the entire page has to be reloaded every few seconds. I am looking for a way to query the database and update only the section of HT ...

Attention: The PageContainer component requires React component classes to extend React.Component

I recently started using react-page-transitions in my project and encountered the following warning message: "PageContainer(...): React component classes must extend React.Component." Here is a snippet of my code: import React from 'react'; ...

The data in my JSON string is not fully received through the HTTP GET request

Whenever I send my array to the PHP file, it receives incomplete data. The content of my 'arr' variable is as follows: [["╪▒┘à┘╛┘╪د","67126881188552864","Empty,Empty,Empty,Empty,8644,-360,-4,8691,-3.48,-313,1015,4.334 M,1392/12/2 ...

Is it possible to switch states in Angular UI Router without altering the URL?

The feature of multiple nested views in the ui-router is quite convenient as it allows for seamless transitions between different states within an application. Sometimes, there may be a need to modify the URL while navigating through states, while at othe ...

Add an item to one ng-repeat by clicking a button in another ng-repeat

I'm trying to manipulate two ng-repeats by adding values from one to the other and vice versa. Here's a snippet of my HTML: <div id="external-events"> <div ng-repeat="selected in selectedcolumn"> <div class="external-event b ...

Ways to implement pointer event styling within a span element

Hi, I'm having trouble with styling and I can't seem to figure out how to resolve it. The style pointer-events: none doesn't seem to be working for me. Here is an example of my code: The style snippet: .noclick { cursor: default; ...

The uploadify plugin in jQuery: onAllComplete event triggered regardless of any errors

I'm currently utilizing the jquery uploadify plugin for enabling users to upload their profile pictures on my ASP.NET MVC platform. As I encountered a few issues, I am seeking assistance: $popup.find('#fileInput').uploadify({ 'uplo ...

What could be causing the Bootstrap navbar to not toggle when the button is clicked?

Attempting to create a website featuring a collapsible navbar, but encountering some issues. The button is properly identified with the correct ID assigned. Jquery and bootstrap have been included in the necessary order at the bottom of the body. However, ...

Is there something I'm overlooking in my image navigation? It doesn't seem to be interactive

Looking for assistance regarding the issue below. I can't seem to make my image clickable, and I'm not sure what's causing this problem. <img src= "makeup.html.jpg" alt= "Make up by Lauren Evans logo" title= "Make ...

Using Angularjs and PHP: incorporating URL parameters into the $http.get() function

I am currently working on a web project in Eclipse with three main files: "controller.js", "home.html," and "array.php". The goal is for the .php file to echo a PHP array encoded in a JSON string: <?php $arr = array(array(title => "hello", auth ...

When it comes to JavaScript, it considers the number 0 as equivalent

I am facing an issue with my spring endpoint that is returning an Enum named StatoPagamentoEnum: Java enum definition @JsonFormat(shape = JsonFormat.Shape.ARRAY) public enum StatoPagamentoEnum { DA_PAGARE(0), PARZIALMENTE_PAGATA(1), PAGATA(2 ...

The items on my list refuse to budge from the left side of the page

There seems to be a formatting issue on my webpage. Ever since I included a Google form, the text is not aligning where I want it to (specifically to the right). .inform { text-align: right; } <section id="iform"> <iframe src="https://docs. ...

Installing MySQL, PHP, and Angular for server deployment

Introduction: I am in the process of setting up a simple CRUD application on a server using PHP, Angular, and a MySQL PhpMyAdmin database. I have used a base template from https://github.com/vpnsingh/Angular-PHP as my starting point. During deployment, I ...

Angular input field for numbers does not display default values

In my stock-status.component.ts file, I have the code snippet below: @Component({ selector: 'app-stock-status', template:` <input type="number" value='0' min='0' required [(ngModel)]='updatedStockValue& ...

Guide on aligning a popup next to the button that activated it using CSS and JavaScript

I am currently generating a dynamic quantity of divs, each containing a button that triggers a popup when clicked. I am attempting to position the popup below the specific button that activated it, but it remains static and does not move accordingly. <d ...