Make a delegated jQuery Auto-complete

271 Views Asked by At

I am using the following code to create an auto-complete textbox. The jQuery is as follows.

$(function() {
   $( "#items .slno" ).autocomplete({
      source: 'search.php'
   });
}); 

The HTML is as follows.

<table id="items">
     <tr class="item-row">
            <td class="item-name"><div class="delete-wpr"><a class="delete" href="javascript:;" title="Remove row">-</a></div></td>
            <td><input type="text" id="slslno" class="slno"/></td>
            <td><input type="text" class="cost"/></td>
            <td><input type="text" class="qty"/></td>
            <!--  <td><span class="price"></span></td>-->
            <td class="price"></td>
            <a class="add" id="addrow" href="javascript:;" title="Add a row">+</a> </tr>

</table>

The Auto-complete works for the first row. However, when the second row is created by clicking on the "Add a row" button in the above code (Its all working fine), the Auto_complete just isn't working on the subsequent rows. I sorted out that I would need a delegated handler for that. SO how can I convert my current jQuery selector to a delegated one?

I Kinda wrote it like the following based on the answer, but it's still not working.

   $('#items').delegate('#items .slno','keyup', function () {   

  $(this).autocomplete({
         source: 'search.php'
    });

  });

Then I went on to use the following.

  $(function(){
  $('#items').on('.slno','keyup.autocomplete', function(){
    $(this).autocomplete({
      source : 'search.php'
    });
  });
});

and it too failed. How do I achieve this?

UPDATE

In the above example, the ordering of the event was messed up. Just needed touse the proper syntax

$(selector).on(event,childSelector,data,function,map)

Which makes my code look like the following.

  $(function(){
  $('#items').on('keyup.autocomplete','.slno', function(){
    $(this).autocomplete({
      source : 'search.php'
    });
  });
});

And it did the task !!!

1

There are 1 best solutions below

0
On

The code below worked for me like a charm.

$(function(){
      $('#items').on('keyup.autocomplete','.slno', function(){
        $(this).autocomplete({
          source : 'search.php'
        });
      });
    });