GuitarGuru
GuitarGuru

Reputation: 45

How do I assign an ID to a row that gets called on buttonclick in javascript

I'm trying to assign an unique id to each row to then modify rows with specific number id's. However since the function is called every time on button click, I always get the same output for the number. Here is my JavaScript Function

[<script type="text/javascript">
    function insert_row(){
      var firstName = document.getElementById('first_name').value;
      var lastName = document.getElementById('last_name').value;
      var human = "human";
      var id =1;

      var table = document.getElementById("saving_table");

      // Create an empty <tr> element and add it to the 1st position of the table:
      var row = table.insertRow(1);
      row.id=id;
      var rowId = row.id;


      // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      var cell3 = row.insertCell(2);

      // Add some text to the new cells:
      cell1.innerHTML = firstName;
      cell2.innerHTML = lastName;
      cell3.innerHTML = human+ rowId.toString();
       id++;
    }
  </script>][1]

Here is my table declaration

<div class="container">
 <table class="table table-bordered" id="saving_table">
    <caption>Classmates</caption>
    <thead>
      <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Human or Vampire?</th>
      </tr>
    </thead>
  </table>
  <button class="btn btn-primary" onclick="insert_row()">Submit</button>

and an image of my output just incase:

Upvotes: 2

Views: 777

Answers (4)

zer00ne
zer00ne

Reputation: 43910

Declare the counter outside of function.

Demo

Details commented in demo

// Reference tags
var btn = document.querySelector('button');
var first = document.getElementById('firstName');
var last = document.getElementById('lastName');
var spec = document.getElementById('species');
// Declare counter
var i = 0;

function insert_row(e) {
  // Reference <tbody> (Not <table>)
  var table = document.querySelector("tbody");
  // Insert <tr> (No index is needed)
  var row = table.insertRow();
  // Add ID to <tr>
  row.id = 'r' + i;
  // for every loop...
  for (let c = 0; c < 3; c++) {
    // ...insert a <td>...
    var cell = row.insertCell(c);
    // ...1st loop add the value of first name input as text...
    if (c === 0) {
      cell.textContent = first.value;
      // ...2nd loop add the value of last name input as text...
    } else if (c === 1) {
      cell.textContent = last.value;
      // ...3rd loop add the value of species select as text...
    } else if (c === 2) {
      cell.textContent = spec.value;
      // ...otherwise just end loop
    } else {
      break;
    }
  }
  // Increment counter
  i++;
}
// Add click event handler to button
btn.onclick = insert_row;
table {
  table-layout: fixed;
  width: 75%;
  margin: 10px auto;
}

th {
  width: 33%
}

td {
  text-align: center
}

caption {
  font-size: 1.2rem;
  font-weight: 900;
}

input,
select,
button {
  display: inline-block;
  font: inherit;
  height: 3ex;
  line-height: 3ex;
  vertical-align: middle;
}

select,
button {
  height: 4ex;
}

button {
  float: right
}
<div class="container">
  <table class="table table-bordered" id="saving_table">
    <caption>Classmates</caption>
    <thead>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Species</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <input id='firstName' placeholder='First'>
  <input id='lastName' placeholder='Last'>
  <select id='species'>
    <option value=''>Species</option>
    <option value='Human &#128373;'>Human &#128373;</option>
    <option value='Vampire &#129499;'>Vampire &#129499;</option>
  </select>
  <button class="btn btn-primary">Submit</button>
</div>

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22320

Please, make better code: 1) increase insertRow for each new line 2) don't repeat all document.getElementById for each call 3) don't mix html code with JS ( onclick="insert_row()" ) 4) If you made a TABLE with THEAD, use TBODY

const
  in_firstName = document.getElementById('first_name'),
  in_lastName  = document.getElementById('last_name'),
  human_str    = "human",
  tableBody    = document.querySelector('#saving_table tbody')
;
var Table_Row_ID = 0;

document.getElementById('insert-row').onclick = function()
{
  // Create an empty <tr> element and add it to the 1st position of the table:
  let row = tableBody.insertRow(Table_Row_ID);
  row.id  = ++Table_Row_ID;

  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
  let
    cell1 = row.insertCell(0),
    cell2 = row.insertCell(1),
    cell3 = row.insertCell(2)
  ;

  // Add some text to the new cells:
  cell1.textContent = in_firstName.value;
  cell2.textContent = in_lastName.value;
  cell3.textContent = human_str + row.id;
}
<div class="container">
  <table class="table table-bordered" id="saving_table">
      <caption>Classmates</caption>
      <thead>
        <tr>
          <th>FirstName</th>
          <th>LastName</th>
          <th>Human or Vampire?</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
</div>
<div class="container">
  <input type="text" id="first_name" placeholder="first_name"   /> 
  <input type="text" id="last_name" placeholder="last_name"   /> 

  <button class="btn btn-primary" id="insert-row">Add Row</button>
</div>

Upvotes: 0

Anuj Khandelwal
Anuj Khandelwal

Reputation: 1244

Since the id variable is being initialized in each function call, all the rows end up having the same id(that is, 1).
One of the ways of solving this would be to simply place the var id = 1; declaration before the start of function insert_row() as a global variable.
However, in order to avoid using global variables, we could get the count of all the existing rows of the table and add 1 to it to get the new id in the following manner:

[<script type="text/javascript">
function insert_row(){
  var firstName = document.getElementById('first_name').value;
  var lastName = document.getElementById('last_name').value;
  var human = "human";

  var table = document.getElementById("saving_table");

  // get count of the number of rows that already exist
  var rowCount = table.getElementsByTagName("tr").length;
  var id = rowCount + 1;

  // Create an empty <tr> element and add it to the 1st position of the table:
  var row = table.insertRow(id);
  row.id=id;
  var rowId = row.id;


  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  // Add some text to the new cells:
  cell1.innerHTML = firstName;
  cell2.innerHTML = lastName;
  cell3.innerHTML = human+ rowId.toString();
   id++;
}

][1]

The HTML code would remain the same. In case your application is large or is headed towards being a large project, I'd strongly recommend using the second method instead of defining a global variable. Global variables tend to get very difficult to manage as the application size grows.

Upvotes: 0

Austin Greco
Austin Greco

Reputation: 33544

Basically you just need to move the id variable outside of the function. That way it's only set to 1 when your code loads, and then each function call increments it.

// global
var id = 1;

function insert_row() {
  // ...

demo

// global
var id = 1;

function insert_row() {
  var firstName = document.getElementById('first_name').value;
  var lastName = document.getElementById('last_name').value;
  var human = "human";

  var table = document.getElementById("saving_table");

  // Create an empty <tr> element and add it to the 1st position of the table:
  var row = table.insertRow(1);
  row.id = id;
  var rowId = row.id;


  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  // Add some text to the new cells:
  cell1.innerHTML = firstName;
  cell2.innerHTML = lastName;
  cell3.innerHTML = human + rowId.toString();
  id++;
}
<div class="container">
 <table class="table table-bordered" id="saving_table">
    <caption>Classmates</caption>
    <thead>
      <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Human or Vampire?</th>
      </tr>
    </thead>
  </table>
  <input id="first_name" />
  <input id="last_name" />
  <button class="btn btn-primary" onclick="insert_row()">Submit</button>
</div>

Upvotes: 1

Related Questions