最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - clone existing div with Jquery - Stack Overflow

programmeradmin1浏览0评论

i have an issue. How can i clone an existing div with jquery?

[Image]1

<div class="modal-body">
    <div class="row">
        <div class="col-md-5 text-center">
            <b>N&uacute;mero Factura</b>
            <input type="number" class="form-control" id="numero"><br/>
        </div>
        <div class="col-md-2 text-center">
            -o-
        </div>
        <div class="col-md-5 text-center">
            <b>N&uacute;mero Remisi&oacute;n</b>
            <input type="number" class="form-control" id="remision"><br/>
        </div>
        <div class="col-md-12">
            <b>NIT:</b>
            <?php $consulta = mysqli_query($conexion, "SELECT * FROM proveedores");
            $resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
            <select class="form-control" id="proveedor">
                <?php foreach($resultado as $r): ?>
                <option value="<?php echo $r['nit']; ?>"><?php echo $r['nombre']; ?></option>
                <?php endforeach; ?>
            </select><br/>
        </div>
        <div class="col-md-2">
            <input type="number" class="form-control" id="productos" value="1">
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-success agregar_producto" name="agregar_producto">
                <i class="fas fa-user-plus" style="color: white"></i>
            </button>
        </div>
    </div>
    <br/>
    <div id="contenido" class="row text-center">
        <div class="col-md-4">
            <b>Producto</b>
            <?php $consulta = mysqli_query($conexion, "SELECT * FROM productos");
            $resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
            <select class="form-control" id="producto">
                <?php foreach($resultado as $r): ?>
                <option value="<?php echo $r['id']; ?>"><?php echo $r['descripcion']; ?></option>
                <?php endforeach; ?>
            </select><br/>
        </div>
        <div class="col-md-4">
            <b>Cantidad</b>
            <input type="number" class="form-control" id="cantidad"><br/>
        </div>
        <div class="col-md-4">
            <b>Precio</b>
            <input type="number" class="form-control" id="precio"><br/>
        </div>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-success crear" name="crear">Agregar Factura</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Regresar</button>
</div>

I need to clone the div with id="contenido" when someone press the button with class="agregar_producto".

How can i solve it? [Example]2

Is it possible? i need only an example to solve my problem. Thx you! <3

EDIT: If a clone this inputs how can i change ids/class to this inputs?

i have an issue. How can i clone an existing div with jquery?

[Image]1

<div class="modal-body">
    <div class="row">
        <div class="col-md-5 text-center">
            <b>N&uacute;mero Factura</b>
            <input type="number" class="form-control" id="numero"><br/>
        </div>
        <div class="col-md-2 text-center">
            -o-
        </div>
        <div class="col-md-5 text-center">
            <b>N&uacute;mero Remisi&oacute;n</b>
            <input type="number" class="form-control" id="remision"><br/>
        </div>
        <div class="col-md-12">
            <b>NIT:</b>
            <?php $consulta = mysqli_query($conexion, "SELECT * FROM proveedores");
            $resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
            <select class="form-control" id="proveedor">
                <?php foreach($resultado as $r): ?>
                <option value="<?php echo $r['nit']; ?>"><?php echo $r['nombre']; ?></option>
                <?php endforeach; ?>
            </select><br/>
        </div>
        <div class="col-md-2">
            <input type="number" class="form-control" id="productos" value="1">
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-success agregar_producto" name="agregar_producto">
                <i class="fas fa-user-plus" style="color: white"></i>
            </button>
        </div>
    </div>
    <br/>
    <div id="contenido" class="row text-center">
        <div class="col-md-4">
            <b>Producto</b>
            <?php $consulta = mysqli_query($conexion, "SELECT * FROM productos");
            $resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
            <select class="form-control" id="producto">
                <?php foreach($resultado as $r): ?>
                <option value="<?php echo $r['id']; ?>"><?php echo $r['descripcion']; ?></option>
                <?php endforeach; ?>
            </select><br/>
        </div>
        <div class="col-md-4">
            <b>Cantidad</b>
            <input type="number" class="form-control" id="cantidad"><br/>
        </div>
        <div class="col-md-4">
            <b>Precio</b>
            <input type="number" class="form-control" id="precio"><br/>
        </div>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-success crear" name="crear">Agregar Factura</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Regresar</button>
</div>

I need to clone the div with id="contenido" when someone press the button with class="agregar_producto".

How can i solve it? [Example]2

Is it possible? i need only an example to solve my problem. Thx you! <3

EDIT: If a clone this inputs how can i change ids/class to this inputs?

Share Improve this question edited Apr 26, 2018 at 6:56 Death-is-the-real-truth 72.3k10 gold badges57 silver badges104 bronze badges asked Apr 26, 2018 at 6:05 Juan MolinaJuan Molina 651 silver badge8 bronze badges 5
  • How about a google search? Stumbled upon this which is from the official jQuery Documentation... – Romeo Sierra Commented Apr 26, 2018 at 6:07
  • Possible duplicate of JQuery clone <select> element – Romeo Sierra Commented Apr 26, 2018 at 6:08
  • If i use clone how can i change id/class to create dinamyc inputs? – Juan Molina Commented Apr 26, 2018 at 6:24
  • codereview.stackexchange./questions/69295/… – Death-is-the-real-truth Commented Apr 26, 2018 at 6:27
  • @JuanMolina When you call $("$elementId").clone() you will get a deep copy of the element which is a jQuery Object. You could use this in a variable probably, to access it's properties.. – Romeo Sierra Commented Apr 26, 2018 at 6:28
Add a ment  | 

5 Answers 5

Reset to default 4

Hi Please check below code:

<html>
      <head>
        <title>Sample HTML</title>
        <script src="https://ajax.googleapis./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      </head>
      <body bgcolor=white>

         <div id="contenido" class="row text-center">
            <div class="col-md-4">
                <b>Producto</b>
                <select class="form-control" id="producto">
                
                    <option value="product1">product1</option>
                    <option value="product2">product2</option>
                    <option value="product3">product3</option>
                    <option value="product4">product4</option>
                    <option value="product5">product5</option>
                    <option value="product6">product6</option>
                    
                </select><br/>
            </div>
            <div class="col-md-4">
                <b>Cantidad</b>
                <input type="number" class="form-control" id="cantidad"><br/>
            </div>
            <div class="col-md-4">
                <b>Precio</b>
                <input type="number" class="form-control" id="precio"><br/>
            </div>
        </div>
        <div class="modal-footer">
        <button type="button" class="btn agregar_producto" name="crear">Agregar Producto</button>
        
    </div>

    <script type="text/javascript">
    jQuery(document).ready(function ($) {
      $(".agregar_producto").on('click', function() {
      
        var $contenido  = $("#contenido:last");
        var $clone = $contenido.clone();
        $clone.find('input').val('');
        $contenido.after($clone);
      });
    });
    </script>
      </body>
    </html>

1.Id need to be unique per element so convert id="contenido" to class="contenido"

2.Use .clone()

$('.agregar_producto').on('click', function(){
  var clone = $( ".contenido:first" ).clone();
  $(clone).attr('id','changedId'); //change cloned element id attribute
  $(clone).find('select').attr('id','changedId1'); //change cloned element children attribute also
  $(clone).insertAfter( ".contenido:last" );
});

Note:- add selector(class or id) of the element after which you want to append the clone.

Reference:-

.insertAfter()

Working snippet:-

$('.agregar_producto').on('click', function(){
  var clone = $( ".contenido:first" ).clone();
  $(clone).attr('id','changedId'); //change cloned element id attribute
  $(clone).find('select').attr('id','changedId1'); //change cloned element children attribute also
  $(clone).insertAfter( ".contenido:last" );
});
#changedId{
 background:yellow;
}

#changedId1{
 font-size:20px;
 color:red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
    <div class="row">
        <div class="col-md-5 text-center">
            <b>N&uacute;mero Factura</b>
            <input type="number" class="form-control" id="numero"><br/>
        </div>
        <div class="col-md-2 text-center">
            -o-
        </div>
        <div class="col-md-5 text-center">
            <b>N&uacute;mero Remisi&oacute;n</b>
            <input type="number" class="form-control" id="remision"><br/>
        </div>
        <div class="col-md-12">
            <b>NIT:</b>
            <?php $consulta = mysqli_query($conexion, "SELECT * FROM proveedores");
            $resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
            <select class="form-control" id="proveedor">
                <?php foreach($resultado as $r): ?>
                <option value="<?php echo $r['nit']; ?>"><?php echo $r['nombre']; ?></option>
                <?php endforeach; ?>
            </select><br/>
        </div>
        <div class="col-md-2">
            <input type="number" class="form-control" id="productos" value="1">
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-success agregar_producto" name="agregar_producto">
                <i class="fas fa-user-plus" style="color: black">Click me to append Clone</i>
            </button>
        </div>
    </div>
    <br/>
    <div class="contenido" class="row text-center">
        <div class="col-md-4">
            <b>Producto</b>
            <select class="form-control" id="producto">
               
                <option value="1">1</option>
                <option value="1">2</option>
                <option value="1">3</option>
                <option value="1">4</option>
                <option value="1">5</option>
                
            </select><br/>
        </div>
        <div class="col-md-4">
            <b>Cantidad</b>
            <input type="number" class="form-control" id="cantidad"><br/>
        </div>
        <div class="col-md-4">
            <b>Precio</b>
            <input type="number" class="form-control" id="precio"><br/>
        </div>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-success crear" name="crear">Agregar Factura</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Regresar</button>
</div>

.clone() method create a deep copy of the set of matched elements. And .appendTo( ) to append the cloned element.

$('.agregar_producto').on('click', function(){
  $( "#contenido" ).clone().appendTo( "body" );
});

$('.agregar_producto').click(function(){
  $( "#contenido" ).clone().appendTo( "body" );
});

you can change the above to append the clone under specific elements.

You could easily do the following.

<div id="div1">
  <p>
    Content in DIV1
  </p>
</div>
<div id="tgt">

</div>

jQuery snippet would be as follows.

$(document).ready(function(){
    var div1 = $("#div1").clone(); //Clone the element. Assigned to the JS variable div1
    div1.attr("id", "div1clone"); //Modify the necessary properties using $(element).attr()
    $("#tgt").append(div1); //Append the content to where ever desired 
});

This is just a very rusty sample. Check this fiddle out to see this in action.

发布评论

评论列表(0)

  1. 暂无评论