2017-08-29 2 views
0

Ich versuche, Daten vom Ende der dynamisch erstellten Dropdownliste neu zu starten.Fügen Sie neue Elemente vom Ende der erstellten Zeilen hinzu.

Szenario ist dies Ich benutze ein von, um mehrere Zeilen Fehler hinzufügen Dropdown-Menüs, die mit einer jQuery-Funktion erstellt werden. Diese Fehler werden unter Verwendung ihrer Fehler-ID in einer Spalte in der Tabelle als eine Zeichenkette gespeichert, die wie folgt aussieht 1,2,3,4 ... usw.

Die Funktionen zum Hinzufügen der Daten funktionieren einwandfrei. Aber das Problem ist, wenn ich versuche, die Daten zu bearbeiten.

Um die Daten zu bearbeiten, verwende ich ein JavaScript, um eine Postanforderung auszulösen, um die Daten aus der Tabelle unten zu ziehen ist der Code, den ich verwende, um die Daten aus den Datentabellen zu erhalten.

HTML: Wo ich die Liste erstellen

<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: Dieses Skript wird auf Last der Datei aufgerufen, um die Daten aus der Tabelle zu ziehen und sie als ausgewählte Elemente gesetzt.

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

In der PHP I der Benutzer Zeit Eintrag ID erhalten dann richtig ErrorId Spalte aus der Tabelle wählen Sie dann, wenn die Spalte dann den Code zu explode die Daten nicht leer laufen an , binden Sie das an die Variable $id in einer foreach Schleife dann erhalten Sie den richtigen Fehlernamen aus der qcErrors Tabelle.

Das obige PHP und das JavaScript funktioniert. Und die Dropdowns werden wie beabsichtigt erstellt, aber wenn ich versuche, ein neues Element hinzuzufügen, indem ich auf die Schaltfläche "Hinzufügen" klicke, wird das neue Drop-down-Menü oben in der Liste erstellt. Bereits vorhandene Dropdown-Menüs werden nach unten verschoben. Egal wie viele Daten vorhanden sind, die Schaltfläche "Hinzufügen" erstellt das neue Element ganz oben.

jQuery: Die Funktion, die ich verwende, um ein neues Element zu erstellen.

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

Ich habe nur die Löschung dort auch. Und die getError() Funktion wird zum Auffüllen der neuen Dropdown-Liste verwendet.

Ich habe versucht, den "Add" Teil zu ändern, um das letzte Element zu finden, aber es wird immer noch an den Anfang der Liste hinzugefügt.

Kann jemand mir bitte zeigen, was ich ändern muss, um die Daten vom Ende der Liste hinzuzufügen.

+0

hilft ich nicht mit zumindest ein Element gefunden konnte der Klassenname 'error-Column' außer in dem Skript, in dem Sie eine neue Zeile hinzufügen möchten. Haben Sie ein solches Element in Ihrem DOM? wenn nicht, korrigieren Sie zuerst den Selektor. dann versuchen Sie wie unten, var $ clone = $ ('. Fehler-Spalte .error-Container: erste'). Clone(); $ ('. Error-Column'). Append ($ clone); Ich hoffe, es wird funktionieren !!! –

+0

Entschuldigung vergessen, den HTML-Teil hinzuzufügen – Sand

+0

Haben Sie versucht, wie ich schon sagte in früheren Kommentar? dh. var $ clone = $ ('. error-Spalte .error-container: first'). clone(); $ ('. error-Column'). append ($ clone); Hoffe, es wird funktionieren !!! –

Antwort

0

Ich löste dieses Problem von mir selbst, also bin ich es als Antwort.

Das Problem war mit dem JavaScript, das ich verwendete, um die Daten für das neue Dropdown zu ziehen. Es gab eine Bedingung, die ich angewendet habe, um den 0 Index zu überspringen. Ich entfernte diese Zeile, als ich die neue Funktion erstellte. Dies war derjenige, der das Problem verursacht hat.

Also änderte ich die JavaScript zurück, die wie folgt aussehen jetzt,

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

Dann bemerkte ich, dass die Schaltfläche ‚Hinzufügen‘ arbeitete, und es wurde das Klonen, aber es war, bevor es die exakte Nachbildung des einen Klonen also war der ausgewählte Wert des Drop-down identisch mit dem oben genannten, der mich verwirrte, also musste ich das ändern. Ich habe das archiviert, indem ich die 'Add' -Funktion mit if-Bedingung geändert habe, die nur dann wirksam wird, wenn eine Benutzer-Zeit-ID-Nummer vorhanden ist.

Neue Add-Funktion:

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

Dann nach, dass ich sah es ein großes Problem mit meinem Drop Tiefen war sie nicht mit der gesamten Fehlerliste aufgefüllt wurden. Nur der richtige Fehler wurde ausgewählt und als ausgewählte Option festgelegt. Nachdem ich stundenlang auf den Monitor gestarrt hatte, gelang es mir, das PHP zu erstellen, das genau das tat, was ich wollte.

PHP-Code:

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

Dies ist der vollständige Code es nicht, dass Rost sein könnte, aber es funktioniert, so hoffen, dass dies jemand in Zukunft

Verwandte Themen