Is the append() function malfunctioning in jQuery?

Why is it copying two lines when I only want one line to be cloned on button click?

Is there a way to make sure that only a single line is copied each time the button is clicked?

Here is my code:

$(function() {
  $('.add-more-room-btn').click(function() {
    let addMoreRoomClone = $(this).parents('.room-info').find('.row:first').html();
    $(this).parents('.room-info').find('.row').append(addMoreRoomClone);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="room-info">
  <div class="row">
    <div class="col-md-12">
      <input type="text" placeholder="this need to copy" />
    </div>
  </div>
  <button class="add-more-room-btn">Add More</button>
</div>

Answer №1

Feel free to utilize the snippet provided for your needs.

$(function() {
  $('.add-more-room-btn').click(function() {
    let addMoreRoomClone = $(this).parents('.room-info').find('.row .col-md-12:first').clone();
    $(this).parents('.room-info').find('.row').append(addMoreRoomClone);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="room-info">
  <div class="row">
    <div class="col-md-12">
      <input type="text" placeholder="this need to copy" />
    </div>
  </div>
  <button class="add-more-room-btn">Add More</button>
</div>

Answer №2

It is clear that you are appending to the .row element, so when you click next, all the contents will be copied. Take a look at my example where I am prepending to the .room-info element and it should work in a similar way.

$(function() {
  $('.add-more-room-btn').click(function() {
    let addMoreRoomClone = $(this).parents('.room-info').find('.row:first').html();
    $(this).parents('.room-info').prepend(addMoreRoomClone);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="room-info">
  <div class="row">
    <div class="col-md-12">
      <input type="text" placeholder="this need to copy" />
    </div>
  </div>
  <button class="add-more-room-btn">Add More</button>
</div>

Answer №3

Your "lines" are .row .col-md-12:first, but you are targeting the first .row instead (which is just one row in the entire document) and appending its .html(). You need to change the selector and correctly copy its contents:

$(function() {

  $('.add-more-room-btn').click(function() {
    // Create a copy of the entire element
    let newContent = $('<div>').append($(this).parents('.room-info').find('.row .col-md-12:first').clone()).html();
    console.log(newContent);
    $(this).parents('.room-info').find('.row').append(newContent);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="room-info">
  <div class="row">
    <div class="col-md-12">
      <input type="text" placeholder="this need to copy" />
    </div>
  </div>

  <button class="add-more-room-btn">Add More</button>

</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

Can you explain the significance of `Component<Props>` in React Native?

Recently, I started a new react-native project and noticed a change in the component syntax. It now reads export default class WelcomeScreen extends Component<Props>, which is different from what it used to be, export default class WelcomeScreen exte ...

Storing a screen value with javascript made simple

I need to incorporate memory functions into my calculator, specifically MS (Memory Store), MR (Memory Restore), and MC (Memory Clear). For Memory Store, the screen value of the calculation needs to be saved, so if it's 90 + 7 = 97, that result should ...

The process of locating a textarea by its id becomes obsolete when integrating CKEDITOR

The data table has editable cells, where clicking on a cell will trigger a bootstrap modal to display with a textarea containing the text retrieved from the database. Snippet of the table structure: <table class="table table-striped table-hover" id="t ...

Having trouble getting Tailwind CSS to work with React components?

I'm having trouble getting Tailwind CSS to work properly. I've made sure to update to the latest version, but for some reason Tailwind is not functioning and there are no errors showing up in the console. Here is a link to my header component an ...

Attempting to acquire multiple responses for a single callback function from multiple requests

I have developed a calculator web application using node.js with express. My goal is to create buttons for addition, subtraction, multiplication, and division operations. While my POST request works fine with a single res.send(), I encountered an issue whe ...

Avoid reloading the header component along with its APIs when navigating routes in React JS

I'm currently working on a web application using react js/next js and within it, I have various pages that make use of globally shared components like the Header and Footer. However, I am facing an issue where I want to prevent unnecessary re-renders ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

The value of Yargs.argv is consistently displayed as [object Object]

In my Ubuntu 16.04 environment, I enrolled in a node.js course on Udemy. Following the instructor's guidance, I initially used the exact version mentioned and later updated to the latest version (11.0.0). Surprisingly, both versions yielded the same o ...

function for handling ajax timeouts

Is it possible to trigger a function when jQuery's $.ajax method reaches its timeout parameter? For instance: $.ajax({ ... ... ,timeout:1000(){do something if timeout) ... }); ...

Unraveling the mystery of extracting special variables from HTML textarea input

How can I parse the input from a textarea using PHP or JS to replace special variables like {name} with an actual name instead of displaying {name} literally? I want users to be able to represent someone's name by entering {name} in their submission. ...

What are your thoughts on having an ajax function that can return either JSON or HTML depending on its success status?

In my jQuery ajax function, I am facing an issue where it responds with HTML if the call fails, and with JSON if the call is successful: {"result":true} $.ajax({ type: 'POST', dataType: 'html', success: func ...

The server encountered an error: TypeError - It is not possible to convert undefined or null into an

Check out this Code import { getProviders, signIn as SignIntoProvider } from "next-auth/react" function handleSignIn({ providers }) { return ( <> {Object.values(providers).map((provider) => ( < ...

Concealing a child component when hovering over its parent element with styled-components

I have a react component structured like this - const MyComponent = () => ( <ContainerSection> <DeleteButtonContainer> <Button theme="plain" autoWidth onClick={() = ...

What is the relationship between font size adjustments and the dimensions of the surrounding parent div element?

I've come across an issue that involves having the following code snippet in the body of an HTML file: html, body { width: 99%; height: 99%; margin: 0px; overflow: hidden; } #container1 { display: flex; gap: 2%; width: 90%; heigh ...

Tips for showing a map in a concealed location: Embed the code in the appropriate location

I've come across solutions for displaying a map in a hidden div, but as a designer and not a programmer, I'm unsure of where to insert the code. The issue is detailed in this post: Click here to view. To resolve the problem, the suggestion is to ...

WordPress Ignoring PHP Generated Elements When Processing Divs

Whenever I attempt to utilize the get_date function, it seems to disregard all div elements and instead places itself right after the header, at the beginning of the <div class="entry-content">. <div class="entry-content"> May 16, ...

Checking the Value of the Second Child Element Using jQuery

I am struggling with a DIV structure that looks like this: <div class="metafield_table"> <div class="metafield"></div> <div class="metafield"></div> <div class="metafield"> ...

Having difficulties loading my stylus stylesheet onto my jade HTML page using expressjs

Within my express application, I am attempting to load the style properties from a styles module engine. Unfortunately, I am facing difficulties in loading my style. Here is the structure of my folders: myNodeApp -node_modules -styles - ...

How do I set up a timing mechanism in a VSCode extension to automatically clear error messages after a specified duration?

I'm currently in the process of developing a VSCode extension, and ran into an issue where I need to display an error message if a certain condition is met. However, I want this error message to automatically disappear after a set amount of time (say, ...

Exploring the use of v-model in Vue3 child components

After some exploration, I recently discovered that in Vue3, the v-model functionality does not work responsively or reactively with child Component. The following code snippet showcases how the username data gets updated: <template> <div> ...