Aniket Singh Aniket Singh - 1 year ago 861
Javascript Question

How to add working dropify inputs dynamically

I have form which gets clone when user click on add more button .

This is how my html looks:

<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
<input type="file" id="drop" class="dropify" data-default-file="" name="sch_logo">
<button class="btn btn-primary btn-duplicator">Add experience</button>

This my jquery part :

$(".btn-duplicator").on("click", function(a) {
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
var d = b.prev(".duplicateable-content");

Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :

function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);

Now after this here is how I initiate the plugin
$('.' + ptr).dropify()

But because id is still same I'm not able to produce clone more than one.

How can I change the id and class everytime user click on it? is there a better way?

Answer Source

Working Fiddle.

Problem : You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.

Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.

Model div code :

<div class='hidden'>
    <div class="col-xs-12 duplicateable-content model">
        <div class="item-block">
            <button class="btn btn-danger btn-float btn-remove">
            <input type="file" data-default-file="" name="sch_logo">
        <button class="btn btn-primary btn-duplicator">Add experience</button>

JS code :

    var drEvent = $('.dropify').dropify();

    $(".btn-duplicator").on("click", clone_model);
    $(".btn-remove").on("click", remove);

    function clone_model() {
        var b = $(this).parent(".duplicateable-content"),
            c = $(".model").clone(true, true);

        c.find('.btn-duplicator').on("click", clone_model);
        c.find('.btn-remove').on("click", remove);

        var d = b.prev(".duplicateable-content");

        drEvent = $('.dropify').dropify();

    function remove() {


Hope this helps.