Sesha Swarup
Sesha Swarup

Reputation: 97

calling .click() script inside another function

Hi I am trying to generate dynamically HTML tables using append(). The way I have written the code is if the user wants to enter the data in the localStorage it first checks if it is empty.If it is empty the code in if block gets executed.If not empty then the else block gets executed.All this code is in the getDetails() JavaScript function. I have given the dynamically generated table id as "myTable".

  <table align="center" id="myTable">

  </table>

  <script>
   function getdetails(){
      if(localStorage.length == 0){
          ......
       }
      else{
          do something ...
      }

      }
  <script>

The issue is that I need to get the row number when I click the table row.For that I have created the following function.

    $(window).load(function() {

     $("#myTable tr").click(function(){
        .....
        });
     });

The above code gets executed (window.load ) when the page refreshes or loads for th first time.But when I add another row in the HTML table( the code exceutes the else block since localStorage is not empty) and click any table row the code doesnt work. Could anyone please tell me on how to get the .click() to work every time.Thanks.

Upvotes: 0

Views: 85

Answers (4)

TSKSwamy
TSKSwamy

Reputation: 225

Try this:

 $("#myTable tr").click(function(){
      alert('You clicked row '+ ($(this).index()+1) );
 });

Source: Which row number is clicked in a table

Upvotes: 1

Innovation
Innovation

Reputation: 1524

Actual problem is you are trying to add click event on row which does not exists when page load.They will load after the execution of script.So the solution for this problem is remove click event from window.load and add it in the script after data population code.

You can also use .on() event of jquery which will work in any case.

Upvotes: 1

Suraj Rawat
Suraj Rawat

Reputation: 3763

Use this

$(document).on('click','#myTable tr',function(){

// your code });

Upvotes: 0

Navin
Navin

Reputation: 604

you can bind the events using on keyword to work on the dynamic DOM elements

Try like this:

$("#myTable").on('click','tr',function(){

        //logic here..

 });

Upvotes: 2

Related Questions