允许编辑文本动态php表 [英] Allow editing of Text dynamic php table

查看:42
本文介绍了允许编辑文本动态php表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过PHP和数据库中的数据生成的html表,我想做的是在每行的最后一个单元格中有一个按钮,上面写着"edit",当您单击该按钮时,其他单元格中的文本变为文本框或其他类型的输入字段,以便您可以对其进行编辑,然后按Submit(提交),该表单将发送出去以在数据库中进行更新.我现在生成表的代码是:

I have a html table that is generated VIA PHP and data in a database, what I want to do is have a button in the last cell of each row that says edit and when you click that button the text in the other cells becomes textboxes or other types of input fields so that you can edit them and then press submit which would send that form off to be updated in the database. The code I have right now to generate the table is:

<table style="width:100%; " class = "table table-striped table-bordered table-hover">
  <tr>
     <th>Name</th>
     <th>Status</th>
     <th>Description</th>
     <?php 
        if($_SESSION['editGroup'] != 0){
           echo "<th>Edit</th>";
        }
     ?>
  </tr>
 <?php
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $checkQuery = "SELECT userGiven, userStatus, userDesc FROM user_Status WHERE organization = 'myOrg' ORDER BY userGiven ASC";
    $prepared = $dbh->prepare($checkQuery);
    $prepared->execute();
    $data = $prepared->fetchAll(PDO::FETCH_ASSOC);
    foreach($data as $row){
      echo "<tr>";
      if($_SESSION['editGroup'] != 0){
      echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='10%'>" . $row['userStatus'] . "</td><td width='70%'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
      }else{
         echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
      }
      echo "</tr>";             
    }
 ?>
</table>

我想做的是将带有userStatus的单元格更改为一个下拉字段,将当前值作为起始值,将另一个值in/out作为另一个值进行选择.

What I am trying to do is change the cell with userStatus to a drop down field with the current value as the starting value and the other value in/out as the other value to select between.

我也想将userDesc更改为一个textarea,我想我知道如何做到这一点,但是当我尝试将其应用于动态表时,我在概念上遇到了问题.

I also want to change the userDesc to a textarea and I think I know how to do all this but I am running into a problem conceptually when I try to apply it to the dynamic table.

我当时想的是,我可以使用jquery/javascript获取可以包围这两个单元格的span变量的innerhtml,然后将html更改为包含当前文本的各种输入字段,从而允许用户对其进行编辑以更改它们价值观.

What I was thinking was that I could use jquery/javascript to get the innerhtml of span variable that could surround those two cells and then change the html to the various input fields containing the current text allowing the user editing them to change those values.

我该如何解决此类问题,我将需要所有按钮的onClick事件,并且我不知道会有多少个按钮,这取决于表中的行数.

How do I do this for this sort of problem though, I would need onClick events for all the buttons and I wouldn't know how many buttons there would be, that's based off of the number of rows in the table.

这将导致数百行冗余代码,因此我认为必须有一种更好的方法.有人知道有什么方法可以做到这一点吗?我发现了这一点: http://stackoverflow.com/questions/16202723/how-to-edit-data-onclick 接近我想要的,但是在我想要的地方似乎是静态值能够对表中的任何行执行此操作.

That would result in hundreds of lines of redundant code so I assume there has to be a much better way. Anyone know what a way to accomplish this? I found this: http://stackoverflow.com/questions/16202723/how-to-edit-data-onclick which is close to what I want but that seems to be static values where I want to be able to do this for any of the rows in the table.

推荐答案

在您的 for 循环中,您需要将可识别的内容放入< tr> < td> 元素.我个人会使用数据属性.例如:

In your for loop, you'll want to put something identifiable in the <tr> and <td> elements. I'd personally go with a data-attribute. For example:

回显行代码

foreach($data as $row){
  echo "<tr data-row='{$row[id]}'>";
  if($_SESSION['editGroup'] != 0){
     echo "<td width='20%' data-column='name'>" . $row['userGiven'] . "</td><td width='10%' data-column='status'>" . $row['userStatus'] . "</td><td width='70%' data-column='description'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
  }else{
     echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
  }
  echo "</tr>";             
}

因此,如您所见,我已经向< tr> 添加了 data-row 属性,该属性应获取数据库记录ID的值.根据需要进行更改-我假设它会被命名为"id".另外,我在< td> 中添加了 data-column 属性,该属性应为我们标识每一列.这是PHP中所需的全部修改.

So, as you can see I've added a data-row attribute to <tr> which should get the value of the database record's ID. Change it as necessary - I made the assumption it'd be named 'id'. Also, I added the data-column attribute to <td> which should identify each column for us. This is all the modification needed in the PHP.

现在,这是编辑按钮的JQuery的样子:

Now, here's what the JQuery for the edit button looks like:

前端事件监听器:第1部分

$( function(){

    $(document).on("click", ".btn-info", function(){

        var parent = $(this).closest("tr");
        var id = $(parent).attr("data-row");
        var name = $(parent).children("[data-column='name']");
        var status = $(parent).children("[data-column='status']");
        var desc = $(parent).children("[data-column='description']");
        var nameTxt = $(name).html();
        var statusTxt = $(status).html();
        var descTxt = $(desc).html();

        $(name).html("<input name='name' data-dc='name' value='" + nameTxt + "'>");
        $(status).html("<input name='status' data-dc='status' value='" + statusTxt + "'>");
        $(desc).html("<textarea name='desc' data-dc='description'>" + descTxt + "</textarea>");

        $(this).replaceWith("<button class='btn-info-save'>Save</button>");
    });

}

最后,我们需要定义在单击保存时会发生什么(上面的示例将编辑"按钮更改为保存"按钮).那可以是任何东西,但是我们假设它将是一个AJAX调用:

Finally, we need to define what happens upon hitting save (the above example changes the "edit" button into a "save" button). That could be anything, but we'll assume it'll be an AJAX call:

前端事件监听器:第2部分

$( function(){

    $(document).on("click", ".btn-info-save", function(){

        var parent = $(this).closest("tr");
        var id = $(parent).attr("data-row");
        var data = {id: id};

        $("[data-dc]").each( function(){
            var col = $(this).attr("data-dc");
            var val = $(this).val();

            data[col] = val;
        });

        $.ajax({
            url: "/dynamic-edit/edit.php", // Change this to your PHP update script!
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function(ret){
                //Do Something
                console.log(ret.response);
               },
            error: function(ret){
                console.log(ret.response);
               }
        });

    });

}

现在,在处理AJAX请求的PHP脚本中:

Now, in your PHP script that handles the AJAX request:

"edit.php"的PHP代码

$name = $_POST['data_name'];
$status = $_POST['data_status'];
$description = $_POST['data_description'];

// Do whatever with the data

// Output JSON - get the response in JS with ret.response
// either inside the success or error portion of the AJAX
echo json_encode( ["response"=>"Row edited successfully."] );

这是一个非常简单的示例,但可以理解这一点.确保将AJAX网址从"/dynamic-edit/edit.php"更改为您要制作PHP脚本的位置,该脚本将在提交后实际进行更新.

This is a very simple example, but it gets the point across. Be sure to change the AJAX url from "/dynamic-edit/edit.php" to wherever you'll make your PHP script that will actually make the updates after submitting.

您可能希望在成功编辑后进行清理;例如,将文本框改回为< td> 中的文本.另外,请注意,我只是将它们更改为文本框.我知道您在帖子中说过,您希望将状态设置为下拉列表,将描述设置为文本区域,但是此示例应该很容易更改.我不知道下拉菜单的值应该是什么,所以您必须做那部分.

You'll likely want to do cleanup after a successful edit; for example, changing the text boxes back to just text in a <td>. Also, please note that I just changed them to textboxes. I know you said in your post you wanted to make one the status a dropdown and the description a textarea, but this example should be easy enough to change. I don't know what the values of the dropdown should be, so you'll have to do that part.

注释

我选择了 $(document).on("click" ... ,而不是 $(.btn-info").on("click" ... ,因为每当您处理动态内容时,您始终都希望在文档而不是元素上使用事件侦听器,为什么呢?因为如果您单击编辑"按钮,它就会消失,而出现保存"按钮,现在将永远失去该事件监听器.如果您要重新添加编辑"按钮(例如,成功保存后),则该按钮将需要再次添加事件监听器.文档,但是,您可以删除/添加所有所需的内容,并且仍然可以使用.

I went with $(document).on("click" ... instead of $(".btn-info").on("click" ... because whenever you're dealing with dynamic content, you always want the event listener on the document, not the element. Why? Because if you click the "edit" button, it disappears and a "save" button appears, you now lose that event listener forever. If you were to re-add the "edit" button (say, after a successful save), that button would need the event listener added again. When you go the route of attaching the event listener to the document, however, you can remove/add all you want and it'll still work.

这篇关于允许编辑文本动态php表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆