0

I have one ajax post function where i get the values from getcontact.php and is append to the htmls . when the html is appended properly when i click on the dynamic contents by using on method the alert function is not working. please help me. My code is as followes

jquery code:

$(document).ready(function(){
$(".val").click(function(){
value = $(this).attr('value');
    $.post('../controller/getcontact.php',
        { id : value , type : 1 },
        function(data) {
           alert(data);
           $("#allUserDiv1").html(data);
        }
    );  
});
$(".allUsers").on("click", function(){ 


alert("hai");

});

});

getcontact.php is as followes

<?php         require_once("../model/regModel.php");
//for adding state and city 
//type = 1 for state and type = 2 for city
      error_reporting(0);
if(isset($_REQUEST['type'])) {

    $type = $_REQUEST['type']; 
    $id   = $_REQUEST['id'];

    $service = new ServiceClass();

    $result_array = array();

    if($type == 1) { //select contact
        $contact = $service->getContact($id);
        while($result = mysql_fetch_array($contact)) {
            $conid   = $result['con_id'];
            $conname = $result['con_name'];                     
            $optionString .= "<li  id=".$conid." class='allUsers' background-color:#CCCCCC;' >".$conname."</li>";
        }

        print_r($optionString);exit();
    }       

}
?>
James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • Where is your HTML? Also don't post code that is not relevant to the question... for example the PHP code. – c0deNinja Jun 10 '14 at 17:58
  • check your jquery version first and try below answer $("#allUserDiv1").on("click", ".allUsers", function(){ alert("hai"); }); – Jain Jun 10 '14 at 18:15

1 Answers1

0

As you mentioned .allUsers is dynamic content, you can't simply attach it to on event handler before creating the element.

Option 1

$("#allUserDiv1").on("click", ".allUsers", function(){ 
alert("hai");
});

Option 2

Add the below method within the ajax success callback, this ensures that the event is attached after the element is created.

$(".allUsers").on("click", function(){ 
alert("hai");
});
Praveen
  • 55,303
  • 33
  • 133
  • 164