如何在表中的多行上运行Javascript函数

时间:2017-06-18 09:58:13

标签: javascript jquery

该函数仅适用于表中的第一行,但在下一行中无法正常工作。有没有人能解决这个问题?提前谢谢

< script >
var rows = document.getElementById(myTable).getElementsByTagName("tr").length;
console.log(rows);
for (var i =0; i<rows;i++){
  (function($, window, document, undefined) {

    $(".addSkip").click(function() {
      var date = new Date($(".start_date").val()),
        days = parseInt($(".days").val(), 10);

      if (!isNaN(date.getTime())) {
        date.setDate(date.getDate() + days);

        $(".end_date").val(date.toInputFormat());
      } else {
        alert("Invalid Date");
      }
    });

    //From: http://stackoverflow.com/questions/3066586/get-string-in-yyyymmdd-format-from-js-date-object
    Date.prototype.toInputFormat = function() {
      var yyyy = this.getFullYear().toString();
      var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
      var dd = this.getDate().toString();
      return yyyy + "-" + (mm[1] ? mm : "0" + mm[0]) + "-" + (dd[1] ? dd : "0" + dd[0]); // padding
    };
  })(jQuery, this, document); <
/script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>

<head>
  <title>Patient Vaccine Detail date entry</title>
</head>

<body>

  <form action="" method="post">

    <h1>New patient Vaccine detail Entry form (date,nextdate entry)</h1>

    <table border='1' cellpadding='10' id="myTable">

      <th>Patient ID</th>
      <th>Vaccine ID</th>
      <th>Vaccine Name</th>
      <th>Total no of injection</th>
      <th>Nth Injection</th>
      <th>Date Injected</th>
      <th>Next Date Injected</th>
      <th>Next Injection Skip</th>

    
      <?php 
session_start();
$pp = $_SESSION['varname7'];
echo $pp;
//get the session variable of vaccineid
$vv = $_SESSION['varname50'];
echo $vv;
?>
      <?php
  // connect to the database
include('connect-db.php');

 $result = mysql_query("SELECT patientvaccine.patientid,
patientvaccine.vaccineid,vaccinedetail.vaccinename,vaccinedetail.totalnoofinjection,
vaccinedetail.nthinjection,
vaccinedetail.date,vaccinedetail.nextdate,vaccinedetail.skip
FROM vaccinetype 
JOIN vaccinedetail ON vaccinedetail.vaccineid = vaccinetype.vaccineid 
JOIN patientvaccine ON patientvaccine.vaccineid = vaccinetype.vaccineid
WHERE patientvaccine.vaccineid = '$vv'")
or die(mysql_error());
?>
        <!-- display data in editabel table with both data from the previous pages using $_SESSION
AND data from Mysql table-->

        <!-- loop through results of database query, displaying them in the table-->

        <?php while($row = mysql_fetch_array( $result )){?>

        <!--echo out the contents of EACH row into a table-->
        <tr>


          <td><input type="text" name="patientid[]" value="<?php echo $pp;?>" \> </td>
          <td><input type="text" name="vaccineid[]" value="<?php echo $vv;?>" \> </td>
          <td><input type="text" name="vaccinename[]" value="<?php echo $row['vaccinename'];?>" \> </td>
          <td><input type="text" name="totalnoofinjection[]" value="<?php echo $row['totalnoofinjection'];?>" \> </td>
          <td><input type="text" name="nthinjection[]" value="<?php echo $row['nthinjection'];?>" \> </td>
          <td><input type="date" name="date[]" class="start_date" value="<?php echo $row['date'];?>" \>
            <input type="button" value="confirm date" class="addSkip"></td>
          <td><input type="text" name="nextdate[]" class="end_date" value="<?php echo $row['nextdate'];?>" \> </td>
          <td><input type="text" name="skip[]" class="days" value="<?php echo $row['skip'];?>" \> </td>

        </tr>

        <?php }?>
    </table><br>
    <input type="submit" name="submit" value="Submit" /></td>
    </tr>
  </form>
  <p><a href="newtype.php">Add a new vaccine</a></p>
  <p><a href="newvdetail2.php">Add new number of injection on current existing vaccine</a></p>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>

</body>

</html>
<!-- Save multiple record of data to mysql database at one submit button using for each loop-->
<?php 
// connect to the database
include('connect-db.php');

// check if the form has been submitted. If it has, start to process the form and save it to the database
// once saved, redirect back to the view page
if (isset($_POST["submit"])){
    foreach ($_POST['patientid'] as $index => $patientid) {
        $data1 = mysql_real_escape_string($patientid);
		$data2 = mysql_real_escape_string($_POST['vaccineid'][$index]);
		$data3 = mysql_real_escape_string($_POST['vaccinename'][$index]);
        $data4 = mysql_real_escape_string($_POST['totalnoofinjection'][$index]);
		$data5 = mysql_real_escape_string($_POST['nthinjection'][$index]);
	    $data6 = mysql_real_escape_string($_POST['date'][$index]);
	    $data7 = mysql_real_escape_string($_POST['nextdate'][$index]);
	    $data8 = mysql_real_escape_string($_POST['skip'][$index]);
        mysql_query("INSERT INTO patientvaccinedetail (patientid,vaccineid,vaccinename, totalnoofinjection,nthinjection,date,nextdate,skip)
		VALUES ('$data1', '$data2','$data3','$data4','$data5','$data6','$data7','$data8')") or die(mysql_error());
    	}
header("Location: start.php");
}
?>

该函数仅适用于表中的第一行,但在下一行中无法正常工作。有没有人能解决这个问题?提前谢谢

2 个答案:

答案 0 :(得分:0)

首先使用var rows = document.getElementById(tableId).getElementsByTagName("tr").length;获取表格中的行数 然后使用for循环多次运行脚本。

答案 1 :(得分:0)

您需要根据单击的按钮隔离每个行实例中的所有字段。

摆脱for()循环并执行以下操作:

$(".addSkip").click(function() {
  // row instance to use `find()` for the other input classes
  var $row = $(this).closest('tr');

  var date = new Date($row.find(".start_date").val()),
    days = parseInt($row.find(".days").val(), 10);

  if (!isNaN(date.getTime())) {
    date.setDate(date.getDate() + days);

    $row.find(".end_date").val(date.toInputFormat());
  } else {
    alert("Invalid Date");
  }
});