Search code examples
jqueryajaxlivesearch

get p tag text in jquery for ajax live search


Hello I have a live search, I send data with ajax and get result search and I can show my result, my result shown in P tag, I wanna access to P tag text in my result search but I cant. please help me

$.ajax({
        url:'<?=base_url();?>report/Chanel/search',
        type: 'POST',
        data: $("#DateForm").serialize(),
        success: function(data){
            if (data == "0")
            {
               $('#livesearch').html('not found any result');
            }
            else
            {
                var dataPo = [];
                var obj = JSON.parse(data);
                for( var i = 0; i < obj.length; i++) {
                    $('#livesearch').append('<p class="ppppp" id="pppp'+i+'">'+obj[i]["channel"].Group_Channel_Name+'</p>')
                    $("#pppp"+i).click(function(){alert($("#pppp"+i).text())});
                 }

            }
        },
        error: function(){
            alert("try again");
        }
});

Solution

  • First, create the "p" and add the event. Finally, append it to liveSearch.

      var obj = [{
      "name": "Ford",
      id: 1
    }, {
      "name": "BMW",
      id: 2
    }, {
      "name": "Fiat",
      id: 3
    }];
    
    $.each(obj, function(index, element) {
      var p = $('<p id="ppp' + element.id + '">' + element.name + '</p>');
      p.click(function(e) {
        console.log($(this).text());
    
      });
    
      $('#livesearch').append(p)
    
    });
    

    https://jsfiddle.net/ua2buz9t/3/