To delegate typeahead on dynamically generated inp

2019-06-13 20:22发布

问题:

I have a html table which i am using to enter the inventory details .In this table I have a input box for product name on which I am binding typeahead event of bootstrap.But the problem is that for the first row input box which is already present on the page when it is rendered, typeahead works fine.But when i add new rows for more entries, typeahead does not works with them.I know about the concept of event delegation but the problem is that I don't know how do i implement it in this case.Kindly guide me through this. Thanks in advance. Here is my html table-

<table>
<thead>
<tr>
<td>Product name</td>
<td>Amount</td>
</tr>
</thead>
<tbody class="details">
<tr>
<td><input type="text class="items" name="items" id="items" data-provide="typeahead" /> </td>
<td><input type="text" name="amt" id="amt" class="amt" /></td>
</tr>
</tbody>
</table>

here is the javascript used to add new rows-

$(function(){
  $('#add').click(function(){
    addnewrow();
  });
});
function addnewrow(){
 var tr = '<tr>'+
'<td><input type="text" name="items" id="items" class="items" data-provide="typeahead" autocomplete="off" /></td>'+
'<td><input type="text" name="amt" id="amt" class="amt" autocomplete="off" /></td>'+
'</tr>';
$('.details').append(tr);
}

Here is the how i have used typeahead-

 $(function(){
    $('#items').typeahead({
  source: function(query,process){
    $.ajax({
         url: 'itemexist.php',
         type: 'POST',
         data: 'query=' +query,
         dataType: 'JSON',
         async: true,
         success: function(data){
          process(data);
         }
    });
  }

  });
});

I know this question has been asked before but there is no accepted solution and I have tried those solutions but it is not working. Here is what I have tried,but still it doesn't seems to work-

$(document).on("keypress",".items",function(){
 $('.items').typeahead({
  source: function(query,process){

    $.ajax({
         url: 'itemexist.php',
         type: 'POST',
         data: 'query=' +query,
         dataType: 'JSON',
         async: true,
         success: function(data){
          process(data);
         }
    });
  }

  });
 });

回答1:

Well I achieved this..I am posting this so that this can help some one else Here's the solution-

 $(function(){
 $('body').delegate('.items','focus',function(){
 $(this).typeahead({
  source: function(query,process){

    $.ajax({
         url: 'itemexist.php',
         type: 'POST',
         data: 'query=' +query,
         dataType: 'JSON',
         async: true,
         success: function(data){
          process(data);
         }
    });
  }

  });
 });
  });