dependent

javascript – Auto select dependent dropdown with jquery json


I have a dynamic and dependent dropdown below. The parent dropdown fetch the active ID from database but how to auto select the child dropdown value that is stored in the same table and set it to “selected”?

Parent Dropdown (php pdo):

<?php

$keynr = new Keynr($db);
$stmt = $keynr->read();

// put them in a select drop-down
echo "<select id='key_dropdown' class='form-control' name='keyindex' required>";
    echo "<option value=''>Wähle Schlüssel...</option>";

    while ($row_content = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row_content);

         // current category of the product must be selected
        **if($position->keyindex==$id){
            echo "<option value='$id' selected>";**
        }else{
            echo "<option value='$id'>";
        }

        echo "$keynr - $content</option>";
    }
      echo "</select>"; 

?>

Child dropdown (Jquery):

<select id='repairkey_dropdown' name='keyindex2' class='form-control' required>
   <option value=''>Wähle Schadensbild ....</option>
</select>

<script>
$(document).ready(function(){
  //pageload
  $(function () {
    $("select#key_dropdown").change();
});
// detect change of dropdown
$("#key_dropdown").change(function(){

    // get id of selected team 
    var key_id=$(this).find(':selected').val();

        // set json url
        var json_url="keys_json.php?key_id=" + key_id;

        // get json data
        jQuery.getJSON(json_url, function(data){

            $("#repairkey_dropdown").html("");
            $("#repairkey_dropdown").append("<option value='0'>Wähle Schadensbild ....</option>");

            jQuery.each(data, function(key, val){
                $("#repairkey_dropdown").append("<option value='" + val.key_repairkey2 + "'>" + val.content + "</option>")
            });

        });
});
});
</script>

Child dropdown (Jquery Json):

<?php 
// set json headers
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');

$key_id=isset($_GET['key_id']) ? $_GET['key_id'] : die('Auftrags ID nicht gefunden.');

include_once '../config/database.php';
include_once '../objects/repairkeys2.php';

$database = new Database();
$db = $database->getConnection();

$repairkey2 = new Repairkey2($db);
$repairkey2->keyindex=$key_id;

$stmt = $repairkey2->readOneAdminDropDown();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($results);
?>

I´m not sure what is the best way to do this.

Thanks! 🙂



لینک منبع