简体   繁体   中英

How to get the count of rows from a dynamic html table?

I have an empty tbody that gets added to whenever a user completes the form. Eventually this table data will be stored in a database, but for now it is not. This is my table setup:

<div class="formContainer">
        <form id="form1">
          <b>Step Number: </b><input type="number" id = "theStep" name="step" required></br>
          <b>First Name: </b> <input type="text" name="firstName" required></br>
          <b>Last Name: </b><input type="text" name="lastName" required></br>
          <b>Alias: </b><input type="text" name="alias" required></br>
          <b>Today's Date: </b><input type="date" id="theDate" name="submitDate" required></br>
          <input type="submit" name="sub" value="submit">
        </form>
      </div>

      <h2>Step Approvals</h2>
      <div class="table-responsive">
        <table id="stepTable" class="table table-striped table-sm">
          <thead>
            <tr>
              <td>Step</td>
              <td>First Name</td>
              <td>Last Name</td>
              <td>Alias</td>
              <td>Submission Date</td>
            </tr>
          </thead>
          <tbody id="displayArea"></tbody>
        </table>
      </div>

I want to automatically fill the form with the entry number so I am trying to keep track of how many entries there are by counting the number of rows in the table. This is what I tried but it only gives me a 'null' value even after I add entries/rows to the table:

var setStep = $('#stepTable > tbody >tr').length;
  if (setStep = 'null') {
    $("#theStep").attr("value", 1)
  } else {
    $("#theStep").attr("value", setStep + 1)
    };

Every time I toggle the form, the 'step' field should be updated with the number of rows in the table + 1.

You can get the row number of a table using document.getElementById("myTable").rows.length

 var rowCount = document.getElementById("myTable").rows.length; // For rows var colCount = document.getElementById("myTable").rows[0].cells.length; // For columns document.getElementById("count").innerHTML = "ROW COUNT: " + rowCount; document.getElementById("count").innerHTML += "<br/>COL COUNT: " + colCount; 
 <table id="myTable" border="1"> <tr> <td> ROW 1 </td> </tr> <tr> <td> ROW 2 </td> </tr> </table> <div id="count"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM