user2970484
user2970484

Reputation: 89

Add OnClick Event with JavaScript or CSS

I have a table in HTML:

    <table id="cust">
        <tr>
            <th>UserName</th>
            <th>Password</th>       
        </tr>       
            <script type="text/javascript">addRows();</script>
        </table>

and I have function in JS that insert Rows to this table. for example:

function addRows() {
  // Get a reference to the table   
  var table = document.getElementById("cust");
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var cell0 = row.insertCell(0);
  var cell1 = row.insertCell(1);
  cell0.innerHTML = "ilan";
  cell1.innerHTML = "11111";
}

but I want that every row that insert to the table, will be with onClick event like that:

<tr onclick="window.document.location='Accounts.html';">

how can I do that?

thank you !!

Upvotes: 1

Views: 3526

Answers (2)

skos
skos

Reputation: 4212

You can use this-

row.setAttribute("onclick","window.document.location='Accounts.html'");

   function addRows() {
      // Get a reference to the table   
      var table = document.getElementById("cust");
      var rowCount = table.rows.length;
      var row = table.insertRow(rowCount);
      row.setAttribute("onclick","window.document.location='Accounts.html'");
      var cell0 = row.insertCell(0);
      var cell1 = row.insertCell(1);
      cell0.innerHTML = "ilan";
      cell1.innerHTML = "11111";
    }

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

Since you are not using any jQuery constructs add a onlick handler to the row element

function addRows() {
    // Get a reference to the table   
    var table = document.getElementById("cust");
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.onclick = rowClick
    var cell0 = row.insertCell(0);
    var cell1 = row.insertCell(1);
    cell0.innerHTML = "ilan";
    cell1.innerHTML = "11111";
}

function rowClick() {
    window.document.location = 'Accounts.html';
}

If you want to have different target locations then

function addRows() {
    // Get a reference to the table   
    var table = document.getElementById("cust");
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.onclick=function(){
        window.document.location='Accounts.html';
    }
    var cell0 = row.insertCell(0);
    var cell1 = row.insertCell(1);
    cell0.innerHTML = "ilan";
    cell1.innerHTML = "11111";
}

Upvotes: 1

Related Questions