To delegate typeahead on dynamically generated input

江枫思渺然 提交于 2019-12-23 04:55:10

问题


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);
         }
    });
  }

  });
 });
  });


来源:https://stackoverflow.com/questions/39181817/to-delegate-typeahead-on-dynamically-generated-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!