行删除后需要重置js行长度

时间:2017-05-04 10:04:58

标签: javascript

他,我差不多完成了我的项目,但我还有一个问题。

当我动态删除表行时,行计数错误。我以为我有解决这个问题的方法。

如何在删除行后重置行的行数。

有人可以解释我做错了什么吗?

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

var removeRowBtn = document.getElementById("removeRowBtn");

// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");

btn.onclick = function() {
  addData()
};

// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
  // first name field check + error
  if (document.myForm.firstName.value == "") {
    alert("Please provide your first name!");
    document.myForm.firstName.focus();
    return false;
  }
  // last name field check + error message
  if (document.myForm.lastName.value == "") {
    alert("Please provide your last name!");
    document.myForm.lastName.focus();
    return false;
  }
  // age field check + error message
  if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
    alert("Please provide your age!");
    return false;
  }
  // country select list check + error message
  if (document.myForm.Country.value == "chooseCountry") {
    alert("Please provide your country!");
    return false;
  }
  // if evry thing is true return a value of true
  return true;
}

function addData() {

  if (validate()) {
    // creating a new tr
    var tr = document.createElement("tr");

    // adding the created elements to a object with a class name
    table.appendChild(tr);
    var rows = " ";

    rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
    tr.innerHTML = rows;

    //console.log(row.length, " 'row length' ");
    //console.log(firstName.value, " 'firstname value' ");
    //console.log(lastName.value, " 'lastName value' ");
    //console.log(age.value, " 'age value' ");
    //console.log(country.value, " 'country value' ");
  }
}

function removeTableRow() {
  var tableNr = document.getElementById("tableNr");
  i = tableNr.value - 1;
  // if there is no table number filled in show a error alert
  if (i == "") {
    alert("Please provide a table number!");
    tableNr.focus();
    return false;
  }

  // find the chosen array
  var row = table.getElementsByTagName("tr")[i];

  // if the number is not in the row show error alert that it issen't in the table
  if (row == undefined) {
    alert("this row number is not in the table");
    return false;
  }

  // remove the selected row
  row.remove(row.selectedIndex);

  // rework the row length
  for (var i = 0; i < row.length; i++) {
    rows[i].cells[0].innerText = row.length;
  }

  console.log(row.length, " 'row lenght' ");
}


removeRowBtn.onclick = function() {
  removeTableRow()
};
body {
  background: white;
}

img {
  height: 100%;
  display: block;
  margin: 0 auto;
}

p {
  text-align: center;
}

.container {
  width: 100%;
  max-width: 600px;
  border-radius: 2px;
  margin: 0 auto;
  margin-top: 8vh;
  background: lightgray;
  box-shadow: 0px 4px 4px darkgray;
}

table {
  width: 100%;
  text-align: center;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}


/* Button */

.btn {
  display: inline-block;
  margin: 1em auto;
  font-weight: 100;
  padding: 1em 1.25em;
  text-align: center;
  width: 100%;
  border-radius: 1px;
  position: relative;
  z-index: 0;
  cursor: pointer;
  border: none;
  background: #0c84e4;
  box-shadow: 0px 1px 1px #063e6b;
  color: #FFFFFF;
}

:focus {
  outline: -webkit-focus-ring-color auto 0px;
}

.btn.red {
  background: red;
  width: 100%;
}


/* input field style's */

input[type=text] {
  width: calc(25% - 8px);
  padding: 12px 20px 12px 5px;
  margin: 8px 4px;
  box-sizing: border-box;
  float: left;
  border: none;
  border-bottom: 2px solid #536DFE;
  text-align: center;
  background: transparent;
}

input:focus {
  outline: none;
  color: black;
}

::-webkit-input-placeholder {
  color: black;
  font: helvetica 12px bold;
  text-align: center;
}

select {
  width: calc(25% - 8px);
  padding: 12px 20px 12px 5px;
  margin: 8px 4px;
  box-sizing: border-box;
  float: left;
  border: none;
  border-bottom: 2px solid #536DFE;
  text-align: center;
  background: transparent;
  height: 39px;
  border-radius: 0px !important;
}
<!DOCTYPE html>
<html>

<head>
  <title>Inzend Opgave H5</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <!-- style sheets -->
  <link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
  <div id="wrapper">
    <section class="container">
      <form id="personInfo" name="myForm">
        <table>
          <thead>
            <tr>
              <td>nr.</td>
              <td>First Name</td>
              <td>Last Name</td>
              <td>Age</td>
              <td>Country</td>
            </tr>
          </thead>
          <tbody id="table">

          </tbody>
        </table>

        <input type="text" name="firstName" placeholder="firstName" id="firstName">
        <input type="text" name="lastName" placeholder="lastName" id="lastName">
        <input type="text" name="Age" placeholder="Age" id="age">
        <select name="Country" id="country">
                  <option value="choose a country">Kies een land</option>
                  <option value="Nederland">NL</option>
                  <option value="Belgie">BE</option>
                  <option value="Duitsland">DE</option>
                </select>

        <input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
        <p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
        <input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
        <input type="text" name="TableNr" id="tableNr" placeholder="table nr.">

      </form>
    </section>
  </div>



  <!-- java-scripts -->
  <script type="text/javascript" src="script.js"></script>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
  <script type="text/javascript">
    var cw = $('.container').width();
    $('.container').css({
      'height': cw + 'px'
    });
  </script>
</body>

</html>

2 个答案:

答案 0 :(得分:0)

Bellow Snippet会给你答案。但是,此row remove函数存在一个小错误。用户必须知道行索引从0开始才能获得第1行。否则将删除错误的行。

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

var removeRowBtn = document.getElementById("removeRowBtn");

// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");

btn.onclick = function() {
  addData()
};

// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
  // first name field check + error
  if (document.myForm.firstName.value == "") {
    alert("Please provide your first name!");
    document.myForm.firstName.focus();
    return false;
  }
  // last name field check + error message
  if (document.myForm.lastName.value == "") {
    alert("Please provide your last name!");
    document.myForm.lastName.focus();
    return false;
  }
  // age field check + error message
  if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
    alert("Please provide your age!");
    return false;
  }
  // country select list check + error message
  if (document.myForm.Country.value == "chooseCountry") {
    alert("Please provide your country!");
    return false;
  }
  // if evry thing is true return a value of true
  return true;
}

function addData() {

  if (validate()) {
    // creating a new tr
    var tr = document.createElement("tr");

    // adding the created elements to a object with a class name
    table.appendChild(tr);
    var rows = " ";

    rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
    tr.innerHTML = rows;

    //console.log(row.length, " 'row length' ");
    //console.log(firstName.value, " 'firstname value' ");
    //console.log(lastName.value, " 'lastName value' ");
    //console.log(age.value, " 'age value' ");
    //console.log(country.value, " 'country value' ");
  }
}

function removeTableRow() {
  var tableNr = document.getElementById("tableNr");
  i = tableNr.value;
  // if there is no table number filled in show a error alert
  if (i == "") {
    alert("Please provide a table number!");
    tableNr.focus();
    return false;
  }

  // find the chosen array
  var row = table.getElementsByTagName("tr")[i];

  // if the number is not in the row show error alert that it issen't in the table
  if (row == undefined) {
    alert("this row number is not in the table");
    return false;
  }

  // remove the selected row
  row.remove(row.selectedIndex);
     
  row = document.getElementById("table").getElementsByTagName("tr");

  // rework the row length
  for (var i = 0; i < row.length; i++) {
    row[i].cells[0].innerText = i+1;
  }

  console.log("Row length: "+ row.length);
}


removeRowBtn.onclick = function() {
  removeTableRow()
};
body {
  background: white;
}

img {
  height: 100%;
  display: block;
  margin: 0 auto;
}

p {
  text-align: center;
}

.container {
  width: 100%;
  max-width: 600px;
  border-radius: 2px;
  margin: 0 auto;
  margin-top: 8vh;
  background: lightgray;
  box-shadow: 0px 4px 4px darkgray;
}

table {
  width: 100%;
  text-align: center;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}


/* Button */

.btn {
  display: inline-block;
  margin: 1em auto;
  font-weight: 100;
  padding: 1em 1.25em;
  text-align: center;
  width: 100%;
  border-radius: 1px;
  position: relative;
  z-index: 0;
  cursor: pointer;
  border: none;
  background: #0c84e4;
  box-shadow: 0px 1px 1px #063e6b;
  color: #FFFFFF;
}

:focus {
  outline: -webkit-focus-ring-color auto 0px;
}

.btn.red {
  background: red;
  width: 100%;
}


/* input field style's */

input[type=text] {
  width: calc(25% - 8px);
  padding: 12px 20px 12px 5px;
  margin: 8px 4px;
  box-sizing: border-box;
  float: left;
  border: none;
  border-bottom: 2px solid #536DFE;
  text-align: center;
  background: transparent;
}

input:focus {
  outline: none;
  color: black;
}

::-webkit-input-placeholder {
  color: black;
  font: helvetica 12px bold;
  text-align: center;
}

select {
  width: calc(25% - 8px);
  padding: 12px 20px 12px 5px;
  margin: 8px 4px;
  box-sizing: border-box;
  float: left;
  border: none;
  border-bottom: 2px solid #536DFE;
  text-align: center;
  background: transparent;
  height: 39px;
  border-radius: 0px !important;
}
<!DOCTYPE html>
<html>

<head>
  <title>Inzend Opgave H5</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <!-- style sheets -->
  <link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
  <div id="wrapper">
    <section class="container">
      <form id="personInfo" name="myForm">
        <table>
          <thead>
            <tr>
              <td>nr.</td>
              <td>First Name</td>
              <td>Last Name</td>
              <td>Age</td>
              <td>Country</td>
            </tr>
          </thead>
          <tbody id="table">

          </tbody>
        </table>

        <input type="text" name="firstName" placeholder="firstName" id="firstName">
        <input type="text" name="lastName" placeholder="lastName" id="lastName">
        <input type="text" name="Age" placeholder="Age" id="age">
        <select name="Country" id="country">
                  <option value="choose a country">Kies een land</option>
                  <option value="Nederland">NL</option>
                  <option value="Belgie">BE</option>
                  <option value="Duitsland">DE</option>
                </select>

        <input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
        <p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
        <input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
        <input type="text" name="TableNr" id="tableNr" placeholder="table nr.">

      </form>
    </section>
  </div>



  <!-- java-scripts -->
  <script type="text/javascript" src="script.js"></script>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
  <script type="text/javascript">
    var cw = $('.container').width();
    $('.container').css({
      'height': cw + 'px'
    });
  </script>
</body>

</html>

答案 1 :(得分:0)

这是我的解决方案我不认为这是最好的方式,但它有效,感谢Inuka的思考帮助。

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

var removeRowBtn = document.getElementById("removeRowBtn");

// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");

btn.onclick = function() {
  addData()
};

// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
  // first name field check + error
  if (document.myForm.firstName.value == "") {
    alert("Please provide your first name!");
    document.myForm.firstName.focus();
    return false;
  }
  // last name field check + error message
  if (document.myForm.lastName.value == "") {
    alert("Please provide your last name!");
    document.myForm.lastName.focus();
    return false;
  }
  // age field check + error message
  if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
    alert("Please provide your age!");
    return false;
  }
  // country select list check + error message
  if (document.myForm.Country.value == "chooseCountry") {
    alert("Please provide your country!");
    return false;
  }
  // if evry thing is true return a value of true
  return true;
}

function addData() {

  if (validate()) {
    // creating a new tr
    var tr = document.createElement("tr");

    // adding the created elements to a object with a class name
    table.appendChild(tr);
    var rows = " ";

    rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
    tr.innerHTML = rows;

    //console.log(row.length, " 'row length' ");
    //console.log(firstName.value, " 'firstname value' ");
    //console.log(lastName.value, " 'lastName value' ");
    //console.log(age.value, " 'age value' ");
    //console.log(country.value, " 'country value' ");
  }
}

function removeTableRow() {
  var tableNr = document.getElementById("tableNr");
  i = tableNr.value - 1;
  // if there is no table number filled in show a error alert
  if (i == "") {
    alert("Please provide a table number!");
    tableNr.focus();
    return false;
  }

  // find the chosen array
  var row = table.getElementsByTagName("tr")[i];

  // if the number is not in the row show error alert that it issen't in the table
  if (row == undefined) {
    alert("this row number is not in the table");
    return false;
  }

  // remove the selected row
  row.remove(row.selectedIndex);

  row = document.getElementById("table").getElementsByTagName("tr");

  // rework the row length
  for (var i = 0; i < row.length; i++) {
    row[i].cells[0].innerText = i+1;
  }

  console.log("Row length: "+ row.length);
}


removeRowBtn.onclick = function() {
  removeTableRow()
};
body{
  background: white;
}
img{
  height: 100%;
  display: block;
  margin: 0 auto;
}
p{
  text-align: center;
}
.container{
  width: 100%;
  max-width: 600px;
  border-radius: 2px;

  margin: 0 auto;
  margin-top: 8vh;

  background: lightgray;
  box-shadow: 0px 4px 4px darkgray;
}


table{
  width: 100%;
  text-align: center;
}
td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}





/* Button */

.btn {
  display: inline-block;
  margin: 1em auto;
  font-weight: 100;
  padding: 1em 1.25em;
  text-align: center;
  width: 100% ;
  border-radius: 1px;
  position: relative;
  z-index: 0;
  cursor: pointer;
  border: none;
  background: #0c84e4;
  box-shadow: 0px 1px 1px #063e6b;
  color: #FFFFFF;
}
:focus {
    outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
  background:red;
  width: 100%;
}


/* input field style's */

input[type=text] {
    width: calc(25% - 8px);
    padding: 12px 20px 12px 5px;
    margin: 8px 4px;
    box-sizing: border-box;
    float: left;
    border: none;
    border-bottom: 2px solid #536DFE;
    text-align: center;
    background: transparent;
}
input:focus{
  outline: none;
  color: black;
}
::-webkit-input-placeholder{
  color:black;
  font: helvetica 12px bold ;
  text-align: center;
}

select{
  width: calc(25% - 8px);
  padding: 12px 20px 12px 5px;
  margin: 8px 4px;
  box-sizing: border-box;
  float: left;
  border: none;
  border-bottom: 2px solid #536DFE;
  text-align: center;
  background: transparent;
  height: 39px;
  border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Inzend Opgave H5</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <!-- style sheets -->
    <link href="style.css" rel="stylesheet" type="text/css" >
  </head>

  <body>
    <div id="wrapper">
      <section class="container">
            <form id="personInfo" name="myForm">
                <table>
                  <thead>
                    <tr>
                      <td>nr.</td>
                      <td>First Name</td>
                      <td>Last Name</td>
                      <td>Age</td>
                      <td>Country</td>
                    </tr>
                  </thead>
                  <tbody id="table">

                  </tbody>
                </table>

                <input type="text" name="firstName" placeholder="firstName" id="firstName">
                <input type="text" name="lastName" placeholder="lastName" id="lastName">
                <input type="text" name="Age" placeholder="Age" id="age">
                <select name="Country" id="country">
                  <option value="choose a country">Kies een land</option>
                  <option value="Nederland">NL</option>
                  <option value="Belgie">BE</option>
                  <option value="Duitsland">DE</option>
                </select>

                <input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
               <p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
                <input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
                <input type="text" name="TableNr" id="tableNr" placeholder="table nr.">

            </form>
      </section>
    </div>



  <!-- java-scripts -->
  <script type="text/javascript" src="script.js"></script>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
  <script type="text/javascript">
      var cw = $('.container').width();
      $('.container').css({
          'height': cw + 'px'
      });
  </script>
  </body>
</html>