Problème de listes déroulantes liées

Résolu
msi79 Messages postés 509 Date d'inscription lundi 24 août 2009 Statut Membre Dernière intervention 2 mai 2023 - 2 sept. 2018 à 13:11
jordane45 Messages postés 38138 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 17 avril 2024 - 4 sept. 2018 à 10:09
Bonjour,
je veux utiliser une code de liste déroulante dans mon projet mais tout se pas passe pas correctement .
voici le code source
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>Dynamic Select Dropdown - Bootsnipp.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        
    </style>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="row">
  <div class="col-md-6 mb-3">
  	<label for="validationCustom03">Category:</label>
      <select class="form-control form-control-lg" name="category" id="validationCustom03" onchange="ChangecatList()" required>
        <option value="">Choose... </option>
        <option value="Classroom Instruction and Assessment">Classroom Instruction and Assessment</option>
        <option value="Curriculum Development and Alignment">Curriculum Development and Alignment</option>
        <option value="District Committee">District Committee</option>
        <option value="Meeting">Meeting</option>
        <option value="Other Category">Other Category</option>
        <option value="Professional Conference">Professional Conference</option>
        <option value="Professional Workshop / Training">Professional Workshop / Training</option>
        <option value="Pupil Services">Pupil Services</option>
      </select>
	<div class="invalid-feedback">
		Please provide a category.
	</div>
  </div>
  <div class="col-md-6 mb-3">
  	<label for="validationCustom04">Activity:</label>
     <select class="form-control form-control-lg" id="validationCustom04" name="activity" required></select>
    <div class="invalid-feedback">
		Please provide an activity.
	</div>
  </div>
</div>
<script type="text/javascript">
var catAndActs = {};
catAndActs['Classroom Instruction and Assessment'] = ['Assessment Day', 'Common Assessment Development', 'Data Team', 'Kindergarten Screening', 'Other'];
catAndActs['Curriculum Development and Alignment'] = ['Capstone Development', 'Course Of Study Development / Revision', 'Standards Alignment / Rollout', 'Other'];
catAndActs['District Committee'] = ['Curriculum Council', 'Grading & Assessment Task Force', 'Professional Development Planning Committee', 'Race To The Top Committee', 'Teacher Evaluation Committee', 'Other'];
catAndActs['Meeting'] = ['Academic Support Team', 'ELL / eKLIP Teachers', 'Gifted Intervention Specialist', 'Intervention Assistance Team', 'Intervention Teachers', 'Kindergarten Parent Conference', 'KLIP Teachers', 'Title I Teachers', 'Other'];
catAndActs['Other Category'] = ['Other'];
catAndActs['Professional Conference'] = ['Conference'];
catAndActs['Professional Workshop / Training'] = ['In-District', 'Out-Of-District'];
catAndActs['Pupil Services'] = ['IEP Meeting', 'IEP Writing'];

function ChangecatList() {
    var catList = document.getElementById("validationCustom03");
    var actList = document.getElementById("validationCustom04");
    var selCat = catList.options[catList.selectedIndex].value;
    while (actList.options.length) {
        actList.remove(0);
    }
    var cats = catAndActs[selCat];
    if (cats) {
        var i;
        for (i = 0; i < cats.length; i++) {
            var cat = new Option(cats[i], i);
            actList.options.add(cat);
        }
    }
} 
</script>
</body>
</html>


voici mon code :
<?php 
  include('connect_pdo.php');
  //VERIF L'EXISTENCE DU TELEPHONE
	 $sql_1 = "SELECT * 
			  FROM tb_sous_famille 
			  ORDER BY design
	         ";

// on envoie la requête
try{
     $req_1 = $pdo->prepare($sql_1);
     $req_1->execute();
     $resulsMDP = $req_1->fetchAll();
}catch(PDOException  $e){
     echo "ERREUR DE REQUETE : " . $sql_1 . '  error : '.$e->getMessage();
}

//echo $sql;
$nbr = !empty($resulsMDP) ? count($resulsMDP) : 0;
   ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>Dynamic Select Dropdown - Bootsnipp.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        
    </style>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="row">
  <div class="col-md-6 mb-3">
  	<label for="validationCustom03">Category:</label>
      <select class="form-control form-control-lg" name="category" id="validationCustom03" onchange="ChangecatList()" required>
        <option value="">Choose... </option>
        <?php 
		  if($nbr > 0):
			foreach($resulsMDP as $result):
		  ?>
        <option value="<?php echo $result["design"] ; ?>"><?php echo $result["design"] ; ?></option>
        <?php 
		   endforeach;
		  endif;
		 ?>
        <option value="Curriculum Development and Alignment">Curriculum Development and Alignment</option>
        <option value="District Committee">District Committee</option>
      </select>
	<div class="invalid-feedback">
		Please provide a category.
	</div>
  </div>
  <div class="col-md-6 mb-3">
  	<label for="validationCustom04">Activity:</label>
     <select class="form-control form-control-lg" id="validationCustom04" name="activity" required></select>
    <div class="invalid-feedback">
		Please provide an activity.
	</div>
  </div>
</div>
<script type="text/javascript">
var catAndActs = {};

        <?php 
		  if($nbr > 0):
			foreach($resulsMDP as $results):
		  ?>
 catAndActs[<?php echo "'".$results["design"]."'" ; ?>] = [
 
														 <?php
														 //EST-IL UN PACK
														$sql_pack = "SELECT *
																	 FROM cree_produit
																	 WHERE id_sousfamille = '".$result["id"]."'
																   ";
														try{
															 $req_pack = $pdo->prepare($sql_pack);
															 $req_pack->execute();
															 $resuls_pack = $req_pack->fetchAll();
														}catch(PDOException  $e){
															 echo "ERREUR DE REQUETE : " . $sql_pack . '  error : '.$e->getMessage();
														}
														
														//echo $sql;
														$nbr_pack = !empty($resuls_pack) ? count($resuls_pack) : 0;
														
														if($nbr_pack >0):
														  foreach($resuls_pack as $saves):
														 ?>
                                                           <?php echo "'".$saves['produit']."'," ; ?> 'Autre'
													    <?php 
														   endforeach;
														  endif;
														 ?>
													];
        <?php 
		   endforeach;
		  endif;
		 ?>





catAndActs['Curriculum Development and Alignment'] = ['Capstone Development', 'Course Of Study Development / Revision', 'Standards Alignment / Rollout', 'Other'];

function ChangecatList() {
    var catList = document.getElementById("validationCustom03");
    var actList = document.getElementById("validationCustom04");
    var selCat = catList.options[catList.selectedIndex].value;
    while (actList.options.length) {
        actList.remove(0);
    }
    var cats = catAndActs[selCat];
    if (cats) {
        var i;
        for (i = 0; i < cats.length; i++) {
            var cat = new Option(cats[i], i);
            actList.options.add(cat);
        }
    }
} 
</script>
</body>
</html>


voici les deux tables :



CREATE TABLE IF NOT EXISTS `cree_produit` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`produit` varchar(150) NOT NULL,
`tva` enum('0','1') NOT NULL,
`code` varchar(15) NOT NULL,
`pa` double NOT NULL,
`prixmin` int(11) NOT NULL,
`prixmax` int(11) NOT NULL,
`tarifEmporte` int(30) NOT NULL,
`tarifHappy` int(30) NOT NULL,
`tarifLivraison` int(30) NOT NULL,
`pointFidelite` int(30) NOT NULL,
`taille` int(11) NOT NULL,
`id_sousfamille` int(11) NOT NULL,
`taux` varchar(15) NOT NULL,
`seuil` int(11) NOT NULL,
`id_fm` int(11) NOT NULL,
`img` varchar(245) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

1 réponse

jordane45 Messages postés 38138 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 17 avril 2024 344
2 sept. 2018 à 17:07
Bonjour,

Ecrit de tête... mais regarde ce que ça donne
<?php 
/**
* Petit rappel
* comment écrire correctement son code en php :
* http://www.commentcamarche.net/faq/48399-php-gestion-des-erreurs-debogage-et-ecriture-du-code
*/


//-------------------------------------------//
//affichage des erreurs php
//-------------------------------------------//
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


//-------------------------------------------//
//connexion à la bdd
//-------------------------------------------//
require_once 'connect_pdo.php';


//-------------------------------------------//
//VERIF L'EXISTENCE DU TELEPHONE
//-------------------------------------------//
 $sql = "SELECT * 
      FROM tb_sous_famille SF
      LEFT JOIN cree_produit P ON P.id_sousfamille = SF.id
      ORDER BY SF.design ";

  try{
     $req_1 = $pdo->prepare($sql);
     $req_1->execute();
     $resulsMDP = $req_1->fetchAll();
  }catch(PDOException  $e){
     echo "ERREUR DE REQUETE : " . $sql . '  error : '.$e->getMessage();
  }
  
  $nbr = !empty($resulsMDP) ? count($resulsMDP) : 0;
  $arrDesigns = array();
  if(!empty($resulsMDP)){
    foreach($resulsMDP a $R){
      $arrDesigns[] = $R['design'];
    }
  }
  $arrPacks = array();
  if(!empty($resulsMDP)){
    foreach($resulsMDP a $R){
      $arrPacks[$R['design']][] = $R['produit'];
    }
  }
  
   ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>Dynamic Select Dropdown - Bootsnipp.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        
    </style>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="row">
  <div class="col-md-6 mb-3">
  	<label for="validationCustom03">Category:</label>
      <select class="form-control form-control-lg" name="category" id="validationCustom03" onchange="ChangecatList()" required>
        <option value="">Choose... </option>
        <?php 
        if(!empty($arrDesigns)){
          foreach($arrDesigns as $D){
            echo '<option value="'.$D["design"].'">.'$D["design"].'</option>';
            
         }
        }
       ?>
        <option value="Curriculum Development and Alignment">Curriculum Development and Alignment</option>
        <option value="District Committee">District Committee</option>
      </select>
	<div class="invalid-feedback">
		Please provide a category.
	</div>
  </div>
  <div class="col-md-6 mb-3">
  	<label for="validationCustom04">Activity:</label>
     <select class="form-control form-control-lg" id="validationCustom04" name="activity" required></select>
    <div class="invalid-feedback">
		Please provide an activity.
	</div>
  </div>
</div>
<script type="text/javascript">
var catAndActs =  <?php echo !empty($resulsMDP) ? json_encode($resulsMDP) : array(); ?>;;
//pour voir dans la console ce que ça donne :
console.log("catAndActs :");
console.log(catAndActs");

catAndActs['Curriculum Development and Alignment'] = ['Capstone Development', 'Course Of Study Development / Revision', 'Standards Alignment / Rollout', 'Other'];

function ChangecatList() {
  var catList = document.getElementById("validationCustom03");
  var actList = document.getElementById("validationCustom04");
  var selCat = catList.options[catList.selectedIndex].value;
  
  actList.innerHTML = "";
  
  var cats = catAndActs[selCat];
  if (cats) {
    for (var i = 0; i < cats.length; i++) {
      var cat = new Option(cats[i], i);
      actList.options.add(cat);
    }
  }
} 
</script>
</body>
</html>

Tu noteras que j'ai évité d'ouvrir fermer les balises php à tout bout de champ.
Tu verras également qu'il est possible de mettre directement un array php dans une variable JS sans avoir besoin d'y faire un boucle.
Par contre, j'ai retravaillé le résultat de la requête avant de m'en servir (j'ai créé deux nouveaux array $arrPacks et $arrDesigns.
J'ai également réalisé qu'une seule requête (via une jointure) au lieu de faire de multiples appels à des requêtes dans des boucles comme tu l'avais fait. (il faut absolument éviter cela ! )

0
msi79 Messages postés 509 Date d'inscription lundi 24 août 2009 Statut Membre Dernière intervention 2 mai 2023 1
2 sept. 2018 à 21:06
bonsoir comme toujours merci pour ta disponibilité.
le code fonctionne toujours pas correctement.

le premier tableau retourne que la première lettre de de la categorie.
ensuite quand je selectionne la deuxième liste deroulante qui devait afficher les produits de cette sous-famille affiche rien.
0
jordane45 Messages postés 38138 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 17 avril 2024 344
2 sept. 2018 à 22:31
Et que t'affiche la CONSOLE ?
vu que je t'ai mis des console.log dans le code javascript... tu devrais pouvoir y voir des choses.....
0
Rejoignez-nous