1

I thought I was doing this correctly but can not seem to get it working and and searching for answers. What I am trying to do is find and retrieve the text from a div that is dynamically created upon the returned information from a ajax call. On the success I am creating a list of divs and dropping numbers in. What I'd like to happen is when that div is clicked on get the value but I'm not getting anything. Here is how the div's are created.

$(".optionsBox").prepend("<div id='newList'>Navigate Pages </div>");
for (var i = 1; i <= ml; i++) {
    $("#newList").append("<div class='paging'>"+ i + "</div>");
}

I've tried:

$('.paging').click(function(){ 
     var number = $this.text();
}); 

$('.paging').on('click',function(){
     var num = $this.text();
});

I've also looked at .closest and even .find When logging to the console everything is blank.

I am obviusly making this harder than it should be.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Troy Bryant
  • 994
  • 8
  • 29
  • 60

2 Answers2

1

Try to use $(this) (the jQuery object constructed with the current element) instead of this and use Jquery .text() to get the text inside current div with class paging clicked :

$('body').on('click', '.paging', function(){
     var number = $(this).text();
});

Hope this helps.


$(".optionsBox").prepend("<div id='newList'>Navigate Pages </div>");
for (var i = 1; i <= 5; i++) {
  $("#newList").append("<div class='paging'>"+ i + "</div>");
}

$('body').on('click', '.paging', function(){
    var number = $(this).text();
  
    $('.result').text('Number ' + number + ' clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="optionsBox"></div>
<div class="result"></div>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

while you using .append ... you can use

$(".optionsBox").on('click', '.paging', function(){
  var number = parseInt($(this).text() , 10);
});

take a look at Event binding on dynamically created elements?

Community
  • 1
  • 1
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28