简体   繁体   English

从创建的行的末尾继续添加新项目

[英]Continue adding new items from the end of the created rows

I'm trying to restart adding data from the end of the dynamically created list of drop downs. 我正在尝试从动态创建的下拉列表的末尾重新开始添加数据。

Scenario is this I use a from to add multiple lines errors using drop downs which are created using a jQuery function. 场景是我使用from来使用使用jQuery函数创建的下拉菜单添加多行错误。 These errors are stored using their error ID in a one column in the table as a string which looks like this 1,2,3,4 ... etc. 这些错误使用它们的错误ID以表中的1,2,3,4 ...等形式存储在表的一列中。

The functions to add the data is working flawlessly. 添加数据的功能运行正常。 But the issue is when I try to edit the data. 但是问题是当我尝试编辑数据时。

To edit the data I use a JavaScript to fire a post request to pull the data from the table below is the code I'm using to get the data from the data tables. 为了编辑数据,我使用JavaScript触发发布请求以从下表中提取数据,这是我用来从数据表中获取数据的代码。

HTML: Where I create the list HTML:创建列表的位置

<div id="jType-container" <?php if ($getTimeDataRow["jType"] == "QC"){?> style="display: block;" <?php } ?>>
    <div id="error-Add-Container">
      <div id="error-Column-Headings">
           Error Number<span>Error Name</span>
      </div>
     <div class="error-Column" id="errorArea">
      <!-- Code is inserted by using the JavaScript which retrieves the data -->
      <!-- from the database-->
     </div>
    </div>
   </div>

JavaScript: This script is called on load of the file to pull the data from the table and set them as selected items. JavaScript:加载文件时调用此脚本,以从表中提取数据并将其设置为选定项。

function getError2(){
    if (document.getElementById("utid").innerHTML !== "") {
        var utid = document.getElementById("utid").innerHTML;
    }else{
        utid = null;
    }

    if(window.XMLHttpRequest){

        xmlhttp=new XMLHttpRequest();

    }else{

        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    }xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){

            document.getElementById("errorArea").innerHTML = xmlhttp.responseText;

        }
    };
    if(utid === null){
        alert("User time ID is not set, Are you sure you're in the right place." );
    }else{
        xmlhttp.open("POST","../functions/getQcErrors.php?utid="+utid,true);
        xmlhttp.send();
    }
}

PHP: PHP:

   $getQcErrors = "SELECT qcErrorId FROM usertimetrack WHERE utId  = :utid";
   $queryQcErrors = $dbConnect -> prepare($getQcErrors);
   $queryQcErrors -> bindParam(':utid', $_REQUEST["utid"]);
   $queryQcErrors -> execute();
   $rowQcError = $queryQcErrors -> fetch(PDO::FETCH_ASSOC);
   $errorNo = 1;

if (!empty($rowQcError["qcErrorId"])){
       foreach (explode(',',$rowQcError["qcErrorId"])as $id){
          $getQcErrors = "SELECT qcId,qcError FROM qcErrors WHERE qcId = :id ORDER BY qcId ASC";
          $queryQcErrors = $dbConnect -> prepare($getQcErrors);
          $queryQcErrors -> bindParam(':id', $id);
          $queryQcErrors -> execute();
       while ($rowErrors = $queryQcErrors -> fetch(PDO::FETCH_ASSOC)){
              echo "<div class='error-container'>";
              echo "<input class='errorCount' size='1' value='".$errorNo."' style='margin-left: 2%' />";
              echo "<select id='errorName' class='errorName'>";
              echo "<option id=".$rowErrors["qcId"].">".$rowErrors["qcError"]."</option>";
              echo "</select>";
              echo "<input class='errorId' size='1' name='errorId' value='".$rowErrors["qcId"]."' hidden readonly>";
              echo "<input type='button' class='addRow' value='Add'/>";
              echo "<input type='button' class='delRow' value='Delete' />";
              echo "</div>";
              $errorNo++;
          }
      }
   }else{
      echo "No data";
}

In the PHP I get the user time entry ID then select correct ErrorId column from the table then if the column is not empty then run the code to explode the data at , bind that to the variable $id in a foreach loop then get the correct error name from the qcErrors table. 在PHP中,我获得了用户时间条目ID,然后从表中选择正确的ErrorId列,然后,如果该列不为空,则运行代码以explode的数据,foreach循环中将其绑定到变量$id ,然后获得正确的qcErrors表中的错误名称。

The above PHP and the JavaScript is working. 上面的PHP和JavaScript正常工作。 And the drop downs are getting created as intended but when I try to add a new item by clicking the "Add" button the new drop down get created at the top of the list already existing drop downs move down. 下拉菜单将按预期方式创建,但是当我尝试通过单击“添加”按钮添加新项目时,将在列表顶部创建新的下拉列表,而现有下拉列表将向下移动。 No matter how many data is there the "Add" button creates the new item at the top. 无论有多少数据,“添加”按钮都会在顶部创建新项目。

jQuery: The function I use to create a new item. jQuery:我用来创建新项目的函数。

// Add and remove function for the error text boxes
$(document).ready(function() {
   $(document).on('click', '.addRow', function() {
     var selectedIndex = $('.errorId').filter(':last').val();
      if(selectedIndex !== ""){
       // $('.error-Column .error-container:last').clone().appendTo('.error-Column');//Clones the row
      // --- Disabled due to is clones and resets the value of the drop down box
         var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
         $clone.find('.errorId').val('');//Find the errorId text box and makes value = ""
         $clone.find('select.errorName').focus();//When cloned set the focus to the error selector

   $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);//Add a row and disables add buttons above
    //resetErrorNo();//Reset the values
   getError();//Pulls the errors from the DB
 }else{
    alert("Select an error name");
 }
}).on('click', '.delRow', function() {
    var $btn = $(this);
     if (confirm('Your sure you want to remove this?')) {
         $btn.closest('.error-container').remove();//Removes the row
          $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);//Enables the last add button
          resetErrorNo();//Reset the values
   }
  }).on('mouseover','.error-container',function () {
    if($('#startTime').val()===""){
       alert("Set job start time");
    }
  });
});

I just left the delete in there as well. 我也只是将删除内容留在那里。 And the getError() function is used for populating the new drop down list. getError()函数用于填充新的下拉列表。

I did try changing the "Add" part to spot the last item but still it adds to the top of the list. 我确实尝试过更改“添加”部分以发现最后一个项目,但仍将其添加到列表的顶部。

Can some one please show me what I need to change in order to add the data from the end of the list. 可以请我告诉我需要做些什么,以便从列表末尾添加数据。

I solved this problem by my self so I'm it as an answer. 我自己解决了这个问题,因此可以作为答复。

The problem was with the JavaScript which I used to pull the data for the new drop down. 问题出在我用来提取新下拉列表数据的JavaScript。 There was a condition which I applied to skip the 0 index, I removed this line line when I was creating the new function. 我有一个条件要跳过0索引,在创建新函数时我删除了该行。 This was the one which was causing the issue. 这是导致问题的原因。

So I changed the JavaScript back which now look like this, 所以我改回了JavaScript,现在看起来像这样,

function getError(){
    //Set the drop down as a variable
    var errorSelect = document.getElementById("errorName");

    if(window.XMLHttpRequest){

        xmlhttp=new XMLHttpRequest();

    }else{

        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    }xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            if(errorSelect.selectedIndex === 0){
                errorSelect.innerHTML = xmlhttp.responseText;
            }
        }
    };
    xmlhttp.open("POST","../functions/getQcErrors.php",true);
    xmlhttp.send();
}

Then I noticed that the 'Add' button was working and it was cloning but it was cloning the exact replica of the one before it so the selected value of the drop down was identical to the above one which confused me so had to change that. 然后我注意到“添加”按钮正在工作,它正在克隆,但是它正在克隆之前的那个按钮的精确副本,因此下拉列表的选定值与上面的相同,这使我感到困惑,因此必须对其进行更改。 I archived that by changing the 'Add' function with if condition which only takes effect only if there's a user time id number. 我通过使用if条件更改“添加”功能来存档,该条件仅在存在用户时间ID号时才生效。

New Add function: 新增功能:

$(document).ready(function() {
    $(document).on('click', '.addRow', function() {
        var selectedIndex = $('.errorId').filter(':last').val();
        if(selectedIndex !== ""){
            // $('.error-Column .error-container:last').clone().appendTo('.error-Column');//Clones the row

            // --- Disabled due to is clones and resets the value of the drop down box
            var $clone = $('.error-Column .error-container:last').clone().appendTo('.error-Column');

            $clone.find('.errorId').val('');//Find the errorId text box and makes value = ""
            if($('#utid').text() !== ""){//Change was made here with this if
               $clone.find('select.errorName').val("----- Select Error -----");
            }
            $clone.find('select.errorName').focus();//When cloned set the focus to the error selector

            $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);//Add a row and disables add buttons above
            resetErrorNo();//Reset the values
            getError();//Pulls the errors from the DB

        }else{
            alert("Select an error name");
        }
    }).on('click', '.delRow', function() {
        var $btn = $(this);
        if (confirm('Your sure you want to remove this?')) {
            $btn.closest('.error-container').remove();//Removes the row
            $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);//Enables the last add button
            resetErrorNo();//Reset the values
        }
    }).on('mouseover','.error-container',function () {
        if($('#startTime').val()===""){
            alert("Set job start time");
        }
    });
});

Then after that I saw there was a big problem with my drop downs they were not populated with the entire error list. 然后,我发现下拉菜单存在很大的问题,它们没有填充整个错误列表。 Only the correct error was selected and set as the selected option. 仅选择了正确的错误,并将其设置为所选选项。 So after staring at the monitor for hours I managed to create the PHP which did exactly what I wanted. 因此,在盯着监视器看了几个小时之后,我设法创建了完全符合我想要的功能的PHP。

PHP Code: PHP代码:

include_once("../iConnect/handShake.php");
if (!isset($_REQUEST["utid"])){
    //This will pull the QC errors from the qcError table.
    $getQcErrors = "SELECT qcId,qcError FROM qcErrors ORDER BY qcId ASC";
    $queryQcErrors = $dbConnect -> query($getQcErrors);
    $queryQcErrors -> execute();

    echo "<option selected disabled>----- Select Error -----</option>";
    while($rowQcError = $queryQcErrors -> fetch(PDO::FETCH_ASSOC)){
        echo "<option id=".$rowQcError["qcId"].">".$rowQcError["qcError"]."</option>";
    }
}else{
    $getQcErrors = "SELECT qcErrorId FROM usertimetrack WHERE utId  = :utid";
    $queryQcErrors = $dbConnect -> prepare($getQcErrors);
    $queryQcErrors -> bindParam(':utid', $_REQUEST["utid"]);
    $queryQcErrors -> execute();
    $rowQcError = $queryQcErrors -> fetch(PDO::FETCH_ASSOC);

    //Initiation of the error number counter
    $errorNo = 1;

    //Used to determine the last element of the table and this will set the last button as enabled
    $len_Array = explode(',',$rowQcError["qcErrorId"]);
    $lineCount = count($len_Array);

    if (!empty($rowQcError["qcErrorId"])){
        foreach (explode(',',$rowQcError["qcErrorId"])as $id){
            //Pull only the matched data set from the table
            $getQcErrors = "SELECT qcId,qcError FROM qcErrors WHERE qcId = :id ORDER BY qcId ASC";
            $queryQcErrors = $dbConnect -> prepare($getQcErrors);
            $queryQcErrors -> bindParam(':id', $id);
            $queryQcErrors -> execute();

            //Pulls the entire data set from the table
            $getQcError = "SELECT qcId,qcError FROM qcErrors ORDER BY qcId ASC";
            $queryQcError = $dbConnect -> query($getQcError);
            $queryQcError -> execute();

            while ($rowErrors = $queryQcErrors -> fetch(PDO::FETCH_ASSOC)){
                echo "<div class='error-container'>";
                echo "<input class='errorCount' size='1' value='".$errorNo."' style='margin-left: 2%' />";
                echo "<select id='errorName' class='errorName'>";
                echo "<option selected disabled>----- Select Error -----</option>";
                while($rowQcError = $queryQcError -> fetch(PDO::FETCH_ASSOC)){
                //If condition which is in brackets will mach the ID's from both queries and set's the selected option
                    echo "<option id=".$rowQcError["qcId"].' '.(($rowQcError["qcId"] == $rowErrors["qcId"])?'selected':"").'>'.$rowQcError["qcError"]."</option>";
                }
                echo "</select>";
                echo "<input class='errorId' size='1' name='errorId' value='".$rowErrors["qcId"]."' hidden readonly>";
                if ($errorNo == $lineCount){
                    echo "<input type='button' class='addRow' value='Add'/>";
                }else{
                    echo "<input type='button' class='addRow' value='Add' disabled/>";
                }
                echo "<input type='button' class='delRow' value='Delete' />";
                echo "</div>";
                $errorNo++;
            }
        }
    }else{
        echo "No data";
    }
}

This is the full code it might not be that grate but it does work, so hope this helps some one in future 这是完整的代码,虽然可能不尽如人意,但确实有用,所以希望这对以后的工作有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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