首页 > 解决方案 > 从输入文本更新表格单元格值

问题描述

这就是我的桌子的样子:

<table id="mytable" border="2" style= "background-color: #f9f9f9; color: #000000; margin: 0 auto;" >
      <thead style= "background-color: #FFFFFF">
        <tr>
          <th>ID</th>
          <th>Goal</th>
          <th>Update</th>
        </tr>
      </thead>
      <tbody>
        <?php
         if ($result = $link->query($query)) {
              $num_rows = 0;
              while ($row = $result->fetch_assoc()) {
                  $num_rows++;
                  
                  echo
                  "<tr>
                  <td>{$row['id']}</td>
                  <td><input type='text' name='goal' id='goal' value='{$row['goal']}'></td>
                  <td><a onClick=\"javascript: return confirm('Are you sure you want to update the goal?');\" href='updategoal.php?id={$row['id']}&goal={$row['goal']}' class='aR'>Update goal</a></td>
                  </tr>";
              }
              /*freeresultset*/
          }
        ?>
      </tbody>
    </table>

updategoal.php这里:

<?php

include "dbase.php"; // Using database connection file here

$unsafe_goal = $_GET['goal'];
$safe_goal = (int)$unsafe_goal;

$unsafe_variable = $_GET['id'];
$safe_variable = (int)$unsafe_variable;

$sql = mysqli_query($link, "UPDATE goals SET goal = $safe_goal WHERE id = $safe_variable");

if($sql)
{
    mysqli_close($link); // Close connection
    header("location:".$_SERVER['HTTP_REFERER']);
    exit;   
}
else
{
    echo "Error deleting record"; // display error message if not updated
}
?>

将鼠标悬停在 上时<a Update goal /a>,url 会显示如下内容:https://example.com/updategoal.php?id=1&goal=10,因此它不会将目标更改为我在输入文本中键入的内容,它只需添加与以前相同的目标即可。有小费吗?

标签: phphtml

解决方案


我花了很长时间才明白你在问什么,但我想我明白了。因此,即使您更新了目标输入字段,也会在页面加载后创建链接并保持相同的值。您需要某种 js 脚本来检查输入值何时更改,然后相应地更改链接。

编辑:我还建议使用类而不是表中的 id。这是一个按预期工作的示例

<table id="mytable" border="2" style= "background-color: #f9f9f9; color: #000000; margin: 0 auto;" >
  <thead style= "background-color: #FFFFFF">
    <tr>
      <th>ID</th>
      <th>Goal</th>
      <th>Update</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>145</td>
      <td><input type='text' name='goal' class='goal' value='2' onkeyup='changeLink(this)'></td>
      <td><a href='updategoal.php?id=145&goal=2' class='aR'>Update goal</a></td>
    </tr>
    <tr>
      <td>146</td>
      <td><input type='text' name='goal' class='goal' value='0' onkeyup='changeLink(this)'></td>
      <td><a href='updategoal.php?id=146&goal=0' class='aR'>Update goal</a></td>
    </tr>
  </tbody>
</table>

function changeLink(input){
  var newGoal = input.value;
  var td = input.parentElement;
  var link_td = td.nextElementSibling;
  var updateLink = link_td.querySelector('a');
  var oldLink = updateLink.href;
  updateLink.href=oldLink.substring(0, oldLink.length-1)+newGoal;
  console.log(updateLink);  
}

https://codepen.io/cst90/pen/zYqOEzL


推荐阅读