0

I'm trying to add a feature of autocomplete, now whatever the result it's returning I'm outputting in the form of a button, but as soon as I apply the click event on dynamically generated button, it doesn't work. Here is my piece of code :

// controller
function autocomplete()
    {
        $string = "";
        $query = $this->db->select('p_sku')->from('fr_products')->like('p_sku',$_POST['sku']);
        $results = $query->get()->result();
        foreach ($results as $result)
        {
            $string .= '<p id='.$result->p_sku.'>'.$result->p_sku.'</p> ';
        }

        echo $string;
    }
    function show_autocomplete()
    {
        $this->load->view('testing/auto');
    }

// view


    <script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#sku').keyup(function(){
            var len = $('#sku').val().length;
            if(len >= 2)
            {
                var value = $('#sku').val();
                $.post(
                    '<?php echo base_url();?>index.php/testing/autocomplete',
                    {sku:value},
                    function(data){
                        $('#feedback').html(data);
                    }
                );
            }
        });
        $('p').click(function(){
            alert('click');
        });
    });
</script>
<input type="text" name="sku" placeholder="SKU1,SKU2,SKU3" id="sku"/>
<div id="feedback"></div>
nbanic
  • 1,248
  • 1
  • 8
  • 11
avinashizhere
  • 485
  • 1
  • 6
  • 21

5 Answers5

2

If you want to bind events to elements that are automatically generated after the script is run, you need to use the on jQuery function. In your case, you can use this code:

$('#feedback').on('click', 'p', function() {
    alert('click');
});
Stefano Dalpiaz
  • 1,483
  • 9
  • 11
1

use Event delegation

try like this:

$("#feedback").on( "click", "p", function(){
  alert("click");
});
Awlad Liton
  • 9,160
  • 2
  • 25
  • 46
0

try like this:

$(document).delegate( "#feedback p","click", function(){
  alert("click");
});
Abdennour TOUMI
  • 64,884
  • 28
  • 201
  • 207
0

try this this will works.

    $(function(){})
    $("#feedback").live( "click", "p", function(){
  alert("click");
});
0

Use on to make activate click event when tags/buttons created dynamically.

$('#feedback').on('click', 'p', function() {
        alert('ButtonCreated');
    });
Runny
  • 9
  • 3