Creating a copy of a div using jQuery's Clone method

I need help figuring out how to clone a div without copying its value. I've attempted various methods, but they all seem to include the value in the cloned element.

This is the jQuery function I am currently using:


$('#add_more').click(function(){
  $('#div_to_clone).clone().insertBefore('#add_more').find('input').val('');
});

Answer №1

Everything seems to be functioning properly for me:

$('#add_more').click(function() {
    $('#div_to_clone').clone().insertBefore('#add_more').find('input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="div_to_clone">
  <input type="text" />
</div>
<a href="#" id="add_more">Add more</a>

I suggest changing the id to a class as the id attribute should be unique on the page. The issue you might be experiencing in some browsers could be due to duplicate id.

$('#add_more').click(function() {
  $('.div_to_clone:first').clone().insertBefore('#add_more').find('input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="div_to_clone">
  <input type="text" />
</div>
<a href="#" id="add_more">Add more</a>

Answer №2

If your HTML code resembles the following:

<div class="ContainerDiv">
<div id=ClonethisDiv><input class="InputTxtBox" type="text" /></div>
</div>
<a href="#">clone</a>

Then, you can use the following jQuery code to clone a specific div and its input element:

$("body").on("click", "a", function() {
    $("#ClonethisDiv").clone().appendTo(".ContainerDiv").find(".InputTxtBox").val("");
});

By clicking on the anchor tag, you will create a copy of the div with ID 'ClonethisDiv' and add it to the container div. When cloning, the input element with class '.InputTxtBox' will be cleared before copying. However, no need to worry as the values of text boxes already in the container div will remain unchanged. I hope this explanation helps!

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

Tips for transferring express route handling to the subsequent middleware and bypassing the current block of code

Here's the current setup of my route handler in my express app: app.use('/', function(res, req, next) => { if (!authorised) next(); f1(); f2(); }); Is there a way to prevent f1() and f2() from running without adding conditional st ...

The format of the date cannot be modified when using DesktopDatePicker as a React Component

I've been attempting to modify the appearance of the component, but the UI keeps showing the date in month-year format. <DesktopDatePicker inputVariant="outlined" label="Pick-up date" id="date ...

"Looking to swap out the Angular theme's CSS stylesheet for your entire application? Here's

I was initially facing an issue while trying to import CSS through index.html as I kept getting a MIME type error: enter image description here The browser refused to apply the stylesheet from 'http://localhost:4200/css/pink-bluegrey.css' because ...

Tips for storing the state using Localstorage?

Greetings to the person reading this message! I am relatively new to programming and I have a query... I created a Navigation bar: body > div > nav > div > ul > li*10 I have implemented the styling in CSS. //Navigation Bar const list = ...

Trouble with HTML img srcset functionality?

I'm currently working on implementing responsive images, and while everything seems to be functioning correctly in the latest version of Firefox, I'm encountering issues with Safari and Chrome. <img src="/images/pages/arrivals/02_exterio ...

The order of event handlers in jQuery

I am currently setting up event binding for a text element dynamically. Take a look at the following code snippet: <input type="text" id="myTxt" /> <script type="text/javascript"> function attachEvent1(element){ element.keyup(func ...

Exploring the Depths with a Javascript Canvas Deep Zoom Library

I am faced with the task of creating a detailed zoom mosaic using an HTML5 Canvas Element, consisting of thousands of roughly 512x512 images. However, I am striving to minimize reinventing the wheel in the process. Instead of merging numerous large images ...

Tips for creating (icon + label) combinations on the initial page of a jQuery mobile application

Is it possible to create a main menu in a jQuery mobile app's first page with icons and labels underneath each icon? <a href="#sport" id="btn1"> <img src="images/sports.png" ; float: center"/> </a><br /> sports ...

To change the font color to red when clicked, I must create a button using HTML, CSS, and Javascript

Currently, I am utilizing CodePen to assess my skills in creating a website. Specifically, I am focusing on the HTML component. My goal is to change the font color to blue for the phrase "Today is a beautiful sunny day!" Here is the snippet of code that I ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

How about connecting functions in JavaScript?

I'm looking to create a custom function that will add an item to my localStorage object. For example: alert(localStorage.getItem('names').addItem('Bill').getItem('names')); The initial method is getItem, which retrieves ...

Transfering data to Handlebars while rendering a template

Is there a method to pass a variable to a handlebars template during its rendering process? Below is the template in question: <script id="listingTopics" type="text/x-handlebars-template"> {{#each this}} <div class="wrapper_individual_listing ...

The bar chart in chartjs is not displaying properly due to incorrect grouping

I attempted to generate a multi bar chart using Chart.js, but encountered an issue where the jobType and jobCount were not displayed correctly based on each companyName. Below is the table: https://i.sstatic.net/ZyKZH.png Here is the PHP file (CompanySel ...

Tips on setting up and managing configuration and registering tasks in Grunt

I've been working on a project that involves using grunt to process my Js and SASS files. The issue I'm facing is that every time I need to make a change, I have to run all the tasks in my gruntfile.js, even if it's just for one module or th ...

Error: THREE.FileLoader does not exist as a constructor

Having difficulty implementing a framework with three.js for an assignment. After cloning this repository and running npm install to download dependencies, the server displays TypeError: THREE.FileLoader is not a constructor. The issue appears to be relat ...

Incorporating z-index into weekly rows within the FullCalendar interface

I'm facing an issue where my detail dropdowns on events are being cropped by the following row. Is there a solution to adjust the z-index of each week row (.fc-row) in the monthly view, arranging them in descending order? For example, setting the z-i ...

Using an `<img>` element as an event handler in a JavaScript function

I'm having trouble setting up a click handler for the search field in my project. I've tried using on() with an img or class, but it's not working as expected. When adding the image using the code below: jQ('#psc').append('&l ...

Tips for implementing dynamic image paths in Next.js

As a newcomer to ReactJS and working with Next.js, I am currently fetching images from a database using an API. The issue I am facing is that I am receiving the image name with the full path (url.com/imagename), but I want to be able to use a dynamic pat ...

Having trouble with React throwing a SyntaxError for an unexpected token?

Error message: Syntax error: D:/file/repo/webpage/react_demo/src/App.js: Unexpected token (34:5) 32 | 33 | return ( > 34 <> | ^ 35 <div className="status">{status}</div> 36 <div className=&quo ...

Combining PageObjects with non-angular pages: is it possible?

I am currently working on writing protractor tests for our application. One specific challenge I have encountered is dealing with a non-angular page within an angular page as an iframe. The issue I am facing is that I cannot properly map fields from the n ...