javascript - How to add working dropify inputs dynamically - Stack Overflow

I have form which gets clone when user click on add more button .This is how my html looks:<div clas

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>
        </button>
        <input type="file" id="drop" class="dropify" data-default-file=".png" name="sch_logo">
    </div>
    <button class="btn btn-primary btn-duplicator">Add experience</button>
    ...
</div>

This my jquery part :

$(function(){ 
    $(".btn-duplicator").on("click", function(a) {
        a.preventDefault();          
        var b = $(this).parent().siblings(".duplicateable-content"),
        c = $("<div>").append(b.clone(true, true)).html();          
        $(c).insertBefore(b);
        var d = b.prev(".duplicateable-content");
        d.fadeIn(600).removeClass("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;
    for(;i++<len;){
      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?

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>
        </button>
        <input type="file" id="drop" class="dropify" data-default-file="https://cdn.example./front2/assets/img/logo-default.png" name="sch_logo">
    </div>
    <button class="btn btn-primary btn-duplicator">Add experience</button>
    ...
</div>

This my jquery part :

$(function(){ 
    $(".btn-duplicator").on("click", function(a) {
        a.preventDefault();          
        var b = $(this).parent().siblings(".duplicateable-content"),
        c = $("<div>").append(b.clone(true, true)).html();          
        $(c).insertBefore(b);
        var d = b.prev(".duplicateable-content");
        d.fadeIn(600).removeClass("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;
    for(;i++<len;){
      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?

Share Improve this question edited Jun 7, 2016 at 15:27 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Jun 7, 2016 at 12:04 user6373207user6373207 1
  • to set a attribute value in JQuery you could use the setter method for attr() e.g. $('#drop').attr('class','YOURCLASSNAME'); or $('#drop').attr('id','YOURIDNAME'); – Lucas Commented Jun 7, 2016 at 12:12
Add a ment  | 

4 Answers 4

Reset to default 2

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">
                X
            </button>
            <input type="file" data-default-file="http://www.misterbilingue./assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
        </div>
        <button class="btn btn-primary btn-duplicator">Add experience</button>
    </div>
</div>

JS code :

$('.dropify').dropify();

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

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

  c.removeClass('model');
  c.find('input').addClass('dropify');

  $(b).before(c);
  $('.dropify').dropify();
}

function remove() {
  $(this).closest('.duplicateable-content').remove();
}

Hope this helps.

Try this:

$(function() {
  $(document).on("click", ".btn-duplicator", function(a) {
    a.preventDefault();
    var b = $(this).parent(".duplicateable-content"),
      c = b.clone(true, true);
    c.find(".dropify").removeClass('dropify').addClass('cropify')
      .attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
    $(c).insertBefore(b);
    var d = b.prev(".duplicateable-content");
    d.fadeIn(600).removeClass("duplicateable-content")
  })
});

Fiddle

This does what you specified with an example different from yours:

<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
    lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
    lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
    $copy.insertAfter('#template');
else
    $copy.insertAfter("#row" + lastId);
}

appendrow();
appendrow();
appendrow();
</script>

Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:

inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );

Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744287343a4566860.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信