Click a button to dynamically create a div element with jQuery

Whenever I click the button to add an address, I want to dynamically create a new div structure using jQuery


<div id="container">
      <div class="address">
           <div class="input-reg rb-item input-group">
                 <span class="input-group-addon">Address </span>
                 <input type="text" class="form-control" placeholder="Insert text here">
           </div>
           <div align="center"><iframe class="map-img" width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?hl=en&amp;ie=UTF8&amp;ll=37.0625,-95.677068&amp;spn=56.506174,79.013672&amp;t=m&amp;z=4&amp;output=embed"></iframe></div>
       </div>
</div>
<div align="center" style="margin-top: 10px"><button id="btnAddAddress" class="btn btn-warning btn-md" type="button">Add Address</button></div>

I have attempted to achieve this functionality but it is not working as intended.


<script type="text/javascript">
    $("#btnAddAddress").click(function () {
      $("#container").append('<div class="address"><div class="input-reg rb-item input-group"><span class="input-group-addon">Address </span><input type="text" class="form-control" placeholder="Insert text here"></div><div align="center"><iframe class="map-img" width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?hl=en&amp;ie=UTF8&amp;ll=37.0625,-95.677068&amp;spn=56.506174,79.013672&amp;t=m&amp;z=4&amp;output=embed"></iframe></div></div>');
    });
</script>

Answer №1

Make sure to wrap your jQuery code within $(document).ready() function like this :-

$(document).ready(function(){
  // Your jQuery code goes here
});

OR

$(document).on('click', '#btnAddAddress', function() 
{...});

Also, remember to include the jQuery library file on your page.

Note: The second method is best suited for dynamically adding HTML to the DOM, otherwise use the first method.

See a working demo here

Answer №2

The functionality of your code is running smoothly, as demonstrated here. I have also streamlined the code for you:

$("#btnAddAddress").click(function () {
     $("#container").append($(".address").html());
});

Answer №3

If you want the code to work without any adjustments, ensure that the JavaScript code is placed after the button in your script.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
      <div class="address">
           <div class="input-reg rb-item input-group">
                 <span class="input-group-addon">Address </span>
                 <input type="text" class="form-control" placeholder="Insert text here">
           </div>
           <div align="center"><iframe class="map-img" width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?hl=en&amp;ie=UTF8&amp;ll=37.0625,-95.677068&amp;spn=56.506174,79.013672&amp;t=m&amp;z=4&amp;output=embed"></iframe></div>
       </div>
</div>
<div align="center" style="margin-top: 10px"><button id="btnAddAddress" class="btn btn-warning btn-md" type="button">Add Address</button></div>

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
    $("#btnAddAddress").click(function () {
      $("#container").append('<div class="address"><div class="input-reg rb-item input-group"><span class="input-group-addon">Address </span><input type="text" class="form-control" placeholder="Insert text here"></div><div align="center"><iframe class="map-img" width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?hl=en&amp;ie=UTF8&amp;ll=37.0625,-95.677068&amp;spn=56.506174,79.013672&amp;t=m&amp;z=4&amp;output=embed"></iframe></div></div>');
    });
</script>

Ensure that the button and jQuery are loaded before executing your code for the best results, as suggested by "Kartikeya".

Answer №4

Make sure to include the statement "return false;" within the click function for proper functionality.

$("#btnAddAddress").click(function () {
   $("#container").append('<div class="address"><div class="input-reg rb-item input-group"><span class="input-group-addon">Address </span><input type="text" class="form-control" placeholder="Insert text here"></div><div align="center"><iframe class="map-img" width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?hl=en&amp;ie=UTF8&amp;ll=37.0625,-95.677068&amp;spn=56.506174,79.013672&amp;t=m&amp;z=4&amp;output=embed"></iframe></div></div>');
   return false;
});

Check out this JSFiddle Example

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

Generating unique names based on input from users

We are working with an array containing names and an input field where users can enter a string to receive name suggestions. The array includes names like Alex and Anna, and when the user types "a," we want to suggest these names. Below is the code snippet ...

Creating a worldwide entity through the use of an Immediately Invoked Function Expression

There are 2 methods I discovered for defining a global object using IIFE: (function () { var func = function () { }; window.func = func; }()); compared to: (function (myFunc) { window.func = myFunc(); }(function () { var func = functi ...

There seems to be an issue with the CSV file, possibly indicating an error or the file may not be an SYLYK file when

After developing a node.js script to convert an array object into CSV format using the "objects-to-csv" library from NPM, I encountered an issue when opening the generated CSV file in WPS and Microsoft Office. The warning suggested that there was either an ...

What is the best way to personalize the HTML Filter in Power-Mezz?

I've been playing around with the HTML Filter feature in the PowerMezz library and I'm interested in customizing the filtering rules for a specific use case. Is this something that can be done? For instance, the default settings allow the style ...

Error: The parameter "callback" must be in the form of a function

Following a tutorial to upload images to Twitter using Node.js with Twit. Here is the code: function upload_random_image(){ console.log('Opening an image...'); var image_path = path.join(__dirname, '/random_cam/' + random_cam()), ...

React Native: Enhance the background with a vibrant stripe of color

I am trying to incorporate a strip of grey in the middle of my white background, but I am encountering an issue where I am unable to input any text inside it. Below is the code snippet I am working with: container: { flex: 1, justifyContent: "cent ...

The HTML Bootstrap collapse feature is not functioning correctly upon the initial button press

Could you assist me with implementing a bootstrap and javascript collapse feature? I have two collapsible cards. The first card should be visible initially, but then switch to the second card when clicked on a link. However, upon the first click, both card ...

.value unable to retrieve form data in JavaScript loops

Whenever I try to utilize the form element, an error pops up indicating that it cannot establish the properties to undefined. The HTML code is as follows: <form name="regForm"> <table> <tr> <!-- First Name --> ...

Leveraging AngularJS directives and $scope autonomously

Let me provide some context first: Previously, my focus was on developing lightweight, single-page Angular applications. However, in the past few days, I began working on a new project that combines Tapestry and Backbone. It has proven to be quite overwhe ...

Converting the stage object to JSON format and incorporating it into an HTML5 environment using

$("#show").click(function(){ var stage = Kinetic.Node.create(json, 'container2'); var ball = new Image(); var cone = new Image(); var tshirt = new Image(); ball.onload = function() { stage.get('.ball').apply ...

Finding a particular sequence of characters and extracting information that comes after it

A while back, I created a website and now I'm looking to transfer the data into a database without manually copying and pasting the 400+ pages it has accumulated. This way, I can transform the site into a database-driven platform. Each page on my sit ...

Tips for adjusting image size in Bootstrap carousel

Is it possible to change the width of the image in this carousel? How can I resize the image without affecting the red box? I've tried numerous solutions on various forums, but none seem to work. The image just won't shrink the way I want it to ...

Consistently retrieving the same array value from the database even after refreshing the page

I am having an issue with the arr variable in my code. It seems to hold the time elements I capture whenever a user pauses a video, but the value of arr remains unchanged every time I refresh the page or perform the activity differently. Does anyone know ...

Determining the dimensions of a div once it has completed loading

Is there a way to retrieve the width and height of a div after it has fully loaded, rather than before? I am currently using JavaScript to get the dimensions, but it seems to be returning the values before the image has finished loading. How can I rectify ...

What is the implementation of booleans within the Promise.all() function?

I am looking to implement a functionality like the following: statusReady: boolean = false; jobsReady: boolean = false; ready() { return Promise.all([statusReady, jobsReady]); } ...with the goal of being able to do this later on: this.ready().then(() ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

Is there an issue with the functionality of the number input type in HTML 5?

<form name="form" method="get" action="" > Number : <input type="number" name="num" id="num" min="1" max="5" required="required"/> <br/> Email : <input type="email" name="email" id="email" required="required"/> <br /> <in ...

Extract the text from an html element by utilizing xpath

This snippet contains HTML content <p class="ref Hover"> <b class="Hover Hover Hover Hover Hover">Manufacturer Part Number:</b> MC34063ADR2G<br> <b>Mounting Method:</b>&nbsp; Surface Mount& ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Issue with dynamic-rooms causing networked Aframe project to malfunction

I am currently working on a project using A-frame() along with the networked A-frame component: https://www.npmjs.com/package/networked-aframe To view the project, click here: I encountered an issue when attempting to replace the following code in scene. ...