Deniz B. Deniz B. - 6 months ago 23
Javascript Question

jQuery Click Function Not Working

jQuery click function not working properly. Actually it works but I'm loading my HTML via JavaScript call after pageload, in this condition jQuery click function not working.

HTML part:

<table class="table table-lg">
<thead>
<tr>
<th width="5%" class="text-center">#</th>
<th width="30%" class="text-center"><?php echo lang('suggestion'); ?></th>
<th width="10%" class="text-center"><?php echo lang('category'); ?></th>
<th width="15%" class="text-center"><?php echo lang('proposer'); ?></th>
<th width="14%" class="text-center"><?php echo lang('date'); ?></th>
<th width="10%" class="text-center"><?php echo lang('likes'); ?></th>
<th width="16%" class="text-center"><?php echo lang('action'); ?></th>
</tr>
</thead>
<tbody id="get_sgs">

<!-- This part is loading by jQuery POST -->
</tbody>
</table>


JavaScript:

<script type="text/javascript">
window.onload = function() {
$.ajax({
url: "<?php echo site_url('get/suggestions'); ?>",
success: function(data){
$("#get_sgs").html(data);
}
});
};
$( "#reload_suggestions" ).click(function() {
$.ajax({
url: "<?php echo site_url('get/suggestions'); ?>",
success: function(data){
$("#get_sgs").html(data);
}
});
});
$('.rate_up').click(function() {
var id = $(this).attr('data-id');
console.log(id);
$.ajax({
url: '<?php echo site_url('rate/up'); ?>' + '/' + id,
type: 'POST',
data: {
'submit': true,
},

});
});
$('.rate_down').click(function() {
var id = $(this).attr('data-id');
console.log(id);
$.ajax({
url: '<?php echo site_url('rate/down'); ?>' + '/' + id,
type: 'POST',
data: {
'submit': true,
},

});
});
</script>


Thanks in advance.

Answer

You have two options:

  1. Bind the click handlers directly after $("#get_sgs").html(data); inside the success block.
  2. Bind the click handlers using $("#get_sgs").on("click", ".rate_down", function() {

See Event binding on dynamically created elements? for a description of the second option.

Comments