Search code examples
jqueryasp.net-mvcjquery-tokeninput

Assign Jquery tokeninput for a dynamically created table row


Edited

Table Template

<table id="Newdiagnosis" style="display:none">
<tr>
 <td><input class="diag" style="width:200px" type="text" name="provider_diagnosis_dtls[#].diagnosis_code" value /></td>
<td><input style="width:500px" type="text" name="provider_diagnosis_dtls[#].diagnosis_desc" value /></td>
<td>
<input type="text" name="provider_diagnosis_dtls[#].diagnosis_level)" readonly value />
<input type="hidden" name="diagnosis.Index" value="%" />
</td>
</tr>
 </table>

Jquery for adding row dynamically

    $(document).ready(function () {
     $("#N").click(function () {
     var index = (new Date()).getTime();
     var clone = $('#Newdiagnosis').clone();
     clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
    clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
     $("#diagnosis").append(clone.html());
     });
 });

I need to attach Jquery tokeniput for each textbox created dynamically. Is it possible?

I tried the below code in Jquery

$("#N").click(function () {
    var index = (new Date()).getTime();
    var clone = $('#Newdiagnosis').clone();
    clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
    clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
    clone.find(".diag").tokenInput("@Url.Action("SearchDiagnosis", "Preapproval")", {
         theme: 'facebook',
         preventDuplicates: true,
         searchingText: 'Searching...',
         tokenLimit: 1
    });
    $("#diagnosis").append(clone.html());
});

This is not searching the data from the action given in url, but the same is working for non-dynamic textbox


Solution

  • You need to attach the plugin to the element after the element has been added to the DOM

    var diagnosis = $("#diagnosis"); // cache it
    $("#N").click(function () {
      var index = (new Date()).getTime();
      var clone = $('#Newdiagnosis').clone();
      clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
      clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
      diagnosis .append(clone.html());
      // Attach the plugin to the new element
      diagnosis.find('.diag').last().tokenInput('@Url.Action("SearchDiagnosis", "Preapproval")', {
        theme: 'facebook',
        preventDuplicates: true,
        searchingText: 'Searching...',
        tokenLimit: 1
      });
    });
    

    Side note: from your comments you indicated some elements have onchange="..". You should remove remove behavior from your markup and use event delegation to handle dynamically added elements

    $("#diagnosis").on('change', '.diag', function() {
      // do something
    });