Search code examples
jqueryjquery-lazyloadbootstrap-tags-input

Bootstrap tags input not working with lazyload


I have a modal that is launched by clicking any one of several images on a page where there is an input field to which I am trying to apply bootstrap-tagsinput.

$(document).on("click","a.lazy",function(){        
        $("#form").find(".title").attr('value',$(this).find(".title").val());
        $("#form").find(".title").attr('data-role','tagsinput');
        $("#form").modal("show");
});

I am assigning the value and data-role attributes with lazyload to the following input field:

<div class="input-group">  
   <span class="input-group-addon">Tags</span>
   <input type="text" class="form-control title" placeholder="Enter Tags for the Image" name="title">
</div>

Once I launch the modal I can see that the attributes are present but the tags are not applied. What am I doing wrong?

<input type="text" class="form-control title" placeholder="Enter Tags for the Image" name="title" value="yellow" data-role="tagsinput">

Solution

  • Just adding data-role is not enough to the input field - because you are adding it dynamically you need to initialise the bootstrap-tags-input like so:

    $(document).on("click","a.lazy",function(){        
            $("#form").find(".title").attr('value',$(this).find(".title").val());
            $("#form").find(".title").attr('data-role','tagsinput');
    
            // Destroy all previous bootstrap tags inputs (optional)
            $('input[data-role="tagsinput"]').tagsinput('destroy');
            // Create the bootstrap tag input UI
            $('input[data-role="tagsinput"]').tagsinput('items');
    
            $("#form").modal("show");
    });