继续从创建的行

时间:2017-08-29 07:00:09

标签: javascript jquery

我正在尝试重新启动从动态创建的下拉列表末尾添加数据。

场景是我使用from来使用使用jQuery函数创建的下拉列表添加多行错误。这些错误使用它们的错误ID存储在表中的一列中,作为一个字符串,看起来像这个1,2,3,4 ......等。

添加数据的功能完美无缺。但问题是当我尝试编辑数据时。

要编辑数据,我使用JavaScript来触发发布请求以从下表中提取数据,这是我用来从数据表中获取数据的代码。

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:在加载文件时调用此脚本以从表中提取数据并将其设置为选定项。

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:

   $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";
}

在PHP中,我获取用户时间条目ID,然后从表中选择正确的ErrorId列,如果列不为空,则将代码运行到explode ,处的数据将其绑定到$id循环中的变量foreach,然后从qcErrors表中获取正确的错误名称。

上面的PHP和JavaScript正在运行。并且按预期创建了下拉菜单,但是当我尝试通过单击“添加”按钮添加新项目时,在列表顶部创建的新下拉菜单已经存在下拉菜单向下移动。无论有多少数据,“添加”按钮都会在顶部创建新项目。

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");
    }
  });
});

我刚刚把删除留在了那里。 getError()函数用于填充新的下拉列表。

我确实尝试更改“添加”部分以找到最后一项,但仍然会将其添加到列表顶部。

有人可以告诉我需要更改的内容,以便从列表末尾添加数据。

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题,所以我就是答案。

问题在于我用来为新下拉提取数据的JavaScript。有一个条件我申请跳过0索引,我在创建新函数时删除了这一行。这是造成这个问题的原因。

所以我改回了现在看起来像这样的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();
}

然后我注意到'添加'按钮正在工作并且它正在克隆但是它正在克隆之前的那个的精确复制品所以下拉的选定值与上面的那个相同,这让我很困惑改变这一点。我通过使用if条件更改“添加”功能来归档,只有在有用户时间ID号时才会生效。

新增功能:

$(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");
        }
    });
});

然后我看到我的下拉有一个很大的问题,他们没有填充整个错误列表。仅选择了正确的错误并将其设置为所选选项。因此,在盯着显示器几个小时后,我设法创建了完全符合我想要的PHP。

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";
    }
}

这是完整的代码,它可能不是那个但它确实有效,所以希望这有助于将来的某个人