Speedy
Speedy

Reputation: 33

Click event not working when the element was changed

I have this <td class="foo">dada</td> and when clicked it triggers an event and it works fine.
and I have this <select> tag that when the selected option changes the text in the <td class="foo"> change too but when the <td> is changed the click event of that element doesn't trigger here's a sample code

<select class="chuchu">
       <option value="1">1</option>
       <option value="2">2</option>
</select>

<table id="tbl">
<tbody>
  <tr>
   <td class="foo">dada</td>
  </tr>
</tbody>
</table>

and here's the script codes that trigger the event click on <td>

<script type="text/javascript">
$('.foo).on('click',function(){
    window.open('url', '_blank');
});
</script>

and this is the script for change event in <select> tag this works fine i just added this for reference for the select tags

$(".chuchu").on("change", function(){
var _val = $(this).val();

$.ajax({
url:"sort_date_attendance.php",
type: "POST",
data: {data:_val},
success:function(response){
  data = JSON.parse(response);
  $("#tbl tbody").html('');
  var html = '';
  for (var i=0; i< data.data.length; i++){
  html +='<tr>'+
            '<td class="foo">'+data.data2[i].stud_lastname+' '+data.data2[i].stud_firstname+'</td>'+                
        '</tr>';
      }
      $("#tbl tbody").html(html);
     }
   });
 });

</script>

Upvotes: 3

Views: 499

Answers (3)

John Bryan Calleja
John Bryan Calleja

Reputation: 128

your td is dynamic try to change this and you miss single quote in your script in click event

<script type="text/javascript">
$('.foo).on('click',function(){
window.open('url', '_blank');
});
</script>

to:

<script type="text/javascript">
$(document).on('click', '.foo',function(){
window.open('url', '_blank');
});
</script>

Upvotes: 2

Amir Mohsen
Amir Mohsen

Reputation: 851

Change your script to this:

<script type="text/javascript">
  $('#tbl').on('click', '.foo',function(){
  window.open('url', '_blank');
 });
</script>

Click event doesn't work on dynamically generated elements

Upvotes: 0

Yusuf Kandemir
Yusuf Kandemir

Reputation: 950

Firtsly change

$('.foo).on('click',function(){
    window.open('url', '_blank');
});

to this

$('.foo').on('click',function(){
    window.open('url', '_blank');
});

Because there is ' missing after foo. And you need to give handler to parents(document is guarenteed option) if target's are changing and added after the handler. So you need to give handler to document for example :

$(document).on('click', '.foo',function(){
  window.open('url', '_blank');
});

Upvotes: 0

Related Questions