Dynamisches Formular - Chained Checkboxes

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • Dynamisches Formular - Chained Checkboxes

    Moin moin,

    Vorweg: Ich bin in Javascript absoluter Anfänger und ich habe nicht einmal ein Referenzhandbuch da.

    Ihr alle kennt sicher miteinander verknüpfte Selectboxen... Die Auswahl eines Elements in Box 1 bestimmt, welche in Box 2 zur Auswahl stehen.

    Das habe ich auch (mit Hilfe von google->snippets) ganz gut hinbekommen.

    Meine Boxen lesen ihre Einträge aus ner MySQL-DB aus. (PHP)

    Jetzt möchte ich aber, dass nach der Auswahl in Box 2 eine Reihe von Checkboxen erscheint, bzw. vorher vorhandene Checkboxen verschwinden.

    Die jeweiligen Checkboxen sollen wiederum mit Name und ID in einer Datenbanktabelle stehen.

    Vielleicht kann mir jemand helfen. Ich habe zwar

    Hier der Code, den ich schon habe.

    start.php:

    Quellcode

    1. <script type="text/javascript" src="ajax.js"></script>
    2. <script type="text/javascript">

    Quellcode

    1. /************************************************************************************************************
    2. Ajax chained select
    3. Copyright (C) 2006 DTHMLGoodies.com, Alf Magne Kalleland
    4. This library is free software; you can redistribute it and/or
    5. modify it under the terms of the GNU Lesser General Public
    6. License as published by the Free Software Foundation; either
    7. version 2.1 of the License, or (at your option) any later version.
    8. This library is distributed in the hope that it will be useful,
    9. but WITHOUT ANY WARRANTY; without even the implied warranty of
    10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    11. Lesser General Public License for more details.
    12. You should have received a copy of the GNU Lesser General Public
    13. License along with this library; if not, write to the Free Software
    14. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    15. Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
    16. written by Alf Magne Kalleland.
    17. Alf Magne Kalleland, 2006
    18. Owner of DHTMLgoodies.com
    19. ************************************************************************************************************/
    20. var ajax = new Array();
    21. function getModelList(sel){
    22. var brand = sel.options[sel.selectedIndex].value;
    23. document.getElementById('model').options.length = 0; // Empty select box
    24. if(brand.length>0){
    25. var index = ajax.length;
    26. ajax[index] = new sack();
    27. ajax[index].requestFile = 'getModels.php?brand='+brand; // Specifying which file to get
    28. ajax[index].onCompletion = function(){ createModels(index) }; // Specify function that will be executed after file has been found
    29. ajax[index].runAJAX(); // Execute AJAX function
    30. }
    31. }
    32. function createModels(index){
    33. var obj = document.getElementById('model');
    34. eval(ajax[index].response); // Executing the response from Ajax as Javascript code
    35. }
    Alles anzeigen

    Quellcode

    1. </script>
    2. <form action="form.php" method="post" name="form" id="form" dir="ltr" lang="de">
    3. <fieldset><legend>Reperaturauftrag</legend>
    4. <p>
    5. <label>Wählen Sie Ihre Marke:</label><br />
    6. <select name="brand" id="brand" size="1" onchange="getModelList(this)" style="width:256px;">
    7. <?php include('getBrands.php'); ?>
    8. </select>
    9. </p>
    10. <p>
    11. <label>Wählen Sie Ihr Modell:</label><br />
    12. <select name="model" id="model" size="1" style="width:256px;">
    13. <? include('getModels.php'); ?>
    14. </select>
    15. </p>
    16. <p>
    17. <label>Was können wir für Sie tun?</label><br />
    18. <!--- Hier sollen die Checks hin! !--->
    19. </p>
    20. <p>
    21. <input type="submit" value=" Absenden ">
    22. <input type="reset" value=" Abbrechen">
    23. </p>
    24. </fieldset>
    25. </form>
    Alles anzeigen


    ajax.js:

    Quellcode

    1. /* Simple AJAX Code-Kit (SACK) v1.6.1 */
    2. /* ©2005 Gregory Wild-Smith */
    3. /* www.twilightuniverse.com */
    4. /* Software licenced under a modified X11 licence,
    5. see documentation or authors website for more details */
    6. function sack(file) {
    7. this.xmlhttp = null;
    8. this.resetData = function() {
    9. this.method = "POST";
    10. this.queryStringSeparator = "?";
    11. this.argumentSeparator = "&";
    12. this.URLString = "";
    13. this.encodeURIString = true;
    14. this.execute = false;
    15. this.element = null;
    16. this.elementObj = null;
    17. this.requestFile = file;
    18. this.vars = new Object();
    19. this.responseStatus = new Array(2);
    20. };
    21. this.resetFunctions = function() {
    22. this.onLoading = function() { };
    23. this.onLoaded = function() { };
    24. this.onInteractive = function() { };
    25. this.onCompletion = function() { };
    26. this.onError = function() { };
    27. this.onFail = function() { };
    28. };
    29. this.reset = function() {
    30. this.resetFunctions();
    31. this.resetData();
    32. };
    33. this.createAJAX = function() {
    34. try {
    35. this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    36. } catch (e1) {
    37. try {
    38. this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    39. } catch (e2) {
    40. this.xmlhttp = null;
    41. }
    42. }
    43. if (! this.xmlhttp) {
    44. if (typeof XMLHttpRequest != "undefined") {
    45. this.xmlhttp = new XMLHttpRequest();
    46. } else {
    47. this.failed = true;
    48. }
    49. }
    50. };
    51. this.setVar = function(name, value){
    52. this.vars[name] = Array(value, false);
    53. };
    54. this.encVar = function(name, value, returnvars) {
    55. if (true == returnvars) {
    56. return Array(encodeURIComponent(name), encodeURIComponent(value));
    57. } else {
    58. this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
    59. }
    60. }
    61. this.processURLString = function(string, encode) {
    62. encoded = encodeURIComponent(this.argumentSeparator);
    63. regexp = new RegExp(this.argumentSeparator + "|" + encoded);
    64. varArray = string.split(regexp);
    65. for (i = 0; i < varArray.length; i++){
    66. urlVars = varArray[i].split("=");
    67. if (true == encode){
    68. this.encVar(urlVars[0], urlVars[1]);
    69. } else {
    70. this.setVar(urlVars[0], urlVars[1]);
    71. }
    72. }
    73. }
    74. this.createURLString = function(urlstring) {
    75. if (this.encodeURIString && this.URLString.length) {
    76. this.processURLString(this.URLString, true);
    77. }
    78. if (urlstring) {
    79. if (this.URLString.length) {
    80. this.URLString += this.argumentSeparator + urlstring;
    81. } else {
    82. this.URLString = urlstring;
    83. }
    84. }
    85. // prevents caching of URLString
    86. this.setVar("rndval", new Date().getTime());
    87. urlstringtemp = new Array();
    88. for (key in this.vars) {
    89. if (false == this.vars[key][1] && true == this.encodeURIString) {
    90. encoded = this.encVar(key, this.vars[key][0], true);
    91. delete this.vars[key];
    92. this.vars[encoded[0]] = Array(encoded[1], true);
    93. key = encoded[0];
    94. }
    95. urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
    96. }
    97. if (urlstring){
    98. this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
    99. } else {
    100. this.URLString += urlstringtemp.join(this.argumentSeparator);
    101. }
    102. }
    103. this.runResponse = function() {
    104. eval(this.response);
    105. }
    106. this.runAJAX = function(urlstring) {
    107. if (this.failed) {
    108. this.onFail();
    109. } else {
    110. this.createURLString(urlstring);
    111. if (this.element) {
    112. this.elementObj = document.getElementById(this.element);
    113. }
    114. if (this.xmlhttp) {
    115. var self = this;
    116. if (this.method == "GET") {
    117. totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
    118. this.xmlhttp.open(this.method, totalurlstring, true);
    119. } else {
    120. this.xmlhttp.open(this.method, this.requestFile, true);
    121. try {
    122. this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    123. } catch (e) { }
    124. }
    125. this.xmlhttp.onreadystatechange = function() {
    126. switch (self.xmlhttp.readyState) {
    127. case 1:
    128. self.onLoading();
    129. break;
    130. case 2:
    131. self.onLoaded();
    132. break;
    133. case 3:
    134. self.onInteractive();
    135. break;
    136. case 4:
    137. self.response = self.xmlhttp.responseText;
    138. self.responseXML = self.xmlhttp.responseXML;
    139. self.responseStatus[0] = self.xmlhttp.status;
    140. self.responseStatus[1] = self.xmlhttp.statusText;
    141. if (self.execute) {
    142. self.runResponse();
    143. }
    144. if (self.elementObj) {
    145. elemNodeName = self.elementObj.nodeName;
    146. elemNodeName.toLowerCase();
    147. if (elemNodeName == "input"
    148. || elemNodeName == "select"
    149. || elemNodeName == "option"
    150. || elemNodeName == "textarea") {
    151. self.elementObj.value = self.response;
    152. } else {
    153. self.elementObj.innerHTML = self.response;
    154. }
    155. }
    156. if (self.responseStatus[0] == "200") {
    157. self.onCompletion();
    158. } else {
    159. self.onError();
    160. }
    161. self.URLString = "";
    162. break;
    163. }
    164. };
    165. this.xmlhttp.send(this.URLString);
    166. }
    167. }
    168. };
    169. this.reset();
    170. this.createAJAX();
    171. }
    Alles anzeigen



    getBrands.php:

    Quellcode

    1. <?php
    2. include('db_config.php');
    3. if (mysqli_connect_errno() == 0){
    4. $sql = 'SELECT `ID`, `name` FROM `brands`';
    5. $result = $db->query( $sql );
    6. while ($row = $result->fetch_object()){
    7. echo '<option value="'.$row->ID.'">'.$row->name.'</option>';
    8. }
    9. $result->close();
    10. }
    11. else
    12. {
    13. echo 'Die Datenbank konnte nicht erreicht werden. Folgender Fehler trat auf: <strong>'.mysqli_connect_errno().' : '.mysqli_connect_error().'</strong>';
    14. }
    15. $db->close();
    16. ?>
    Alles anzeigen


    getModels.php:

    Quellcode

    1. <?php
    2. if(isset($_GET['brand'])){
    3. include('db_config.php');
    4. if (mysqli_connect_errno() == 0){
    5. $sql = 'SELECT `ID`, `brandID`, `name` FROM `models` WHERE brandID="'.$_GET['brand'].'" ORDER BY `ID` DESC';
    6. $result = $db->query( $sql );
    7. while ($row = $result->fetch_object()){
    8. echo "obj.options[obj.options.length] = new Option('".$row->name."','".$row->ID."');\n";
    9. }
    10. $result->close();
    11. }
    12. else
    13. {
    14. echo 'Die Datenbank konnte nicht erreicht werden. Folgender Fehler trat auf: <strong>'.mysqli_connect_errno().' : '.mysqli_connect_error().'</strong>';
    15. }
    16. $db->close();
    17. } else {
    18. include('db_config.php');
    19. if (mysqli_connect_errno() == 0){
    20. $sql = 'SELECT `ID`, `brandID`, `name` FROM `models` WHERE brandID="1" ORDER BY `ID` DESC';
    21. $result = $db->query( $sql );
    22. while ($row = $result->fetch_object()){
    23. echo '<option value="'.$row->ID.'">'.$row->name.'</option>';
    24. }
    25. $result->close();
    26. }
    27. else
    28. {
    29. echo 'Die Datenbank konnte nicht erreicht werden. Folgender Fehler trat auf: <strong>'.mysqli_connect_errno().' : '.mysqli_connect_error().'</strong>';
    30. }
    31. $db->close();
    32. }
    33. ?>
    Alles anzeigen


    Die dbconfig.php geb ich mal nich raus. Versteht sich denk ich... DB läuft ja auch.
  • Ja, ungefähr. Nur eben, dass ich das schon habe. Was mir fehlt wäre eine Beschreibung, wie ich auf diese Art (also via onChange-Event je nach Auswahl in der letzten Selectbox) Checkboxen baue... Ich hab google schon gefragt, aber ich finde immer nur, wie man die stylet (was ich selbst kann) oder wie man die setzt bzw. cleart.
  • Jetzt möchte ich aber, dass nach der Auswahl in Box 2 eine Reihe von Checkboxen erscheint, bzw. vorher vorhandene Checkboxen verschwinden.

    Was mir fehlt wäre eine Beschreibung, wie ich auf diese Art (also via onChange-Event je nach Auswahl in der letzten Selectbox) Checkboxen baue...

    Mir ist leider immer noch nicht ganz klar, was dir fehlt.

    Du willst statt einer Auswahlliste Checkboxen haben? Checkboxen erlauben ja im Gegensatz zu radio und Select Formularen eine Mehrfachauswahl. Willst du das erreichen?
  • OK, dann beschreibe ich jetzt einfach mal mein Vorhaben im Detail.

    1.) Man wählt seine Handymarke
    2.) Man wählt sein Modell (wobei in der Selectbox nur die zur Marke gehörigen Modelle gezeigt werden...)
    3.) Man wählt aus verschiedenen Reperaturdienstleistungen aus. (Die wiederum vom Handy abhängen...) Hier soll Mehrfachwahl möglich sein.
    Zusätzlich kann man in ne Textbox Wünsche schreiben, die dann überprüft werden, aber das geht bei jeder Marke ist also statisch.

    Was ich will, ist dass eben je nach Marke und Modell nur bestimmte Checkboxen vorhanden sind. Deshalb müsste ich die über Javascript (oder PHP, wenn das möglich wäre) je nach Auswahl extra bauen.
  • Okay, das Ziel ist nun klar.

    Was hast du schon? Das solltest du mit den bisherigen Kenntnissen bauen können.

    Meilenstein 1
    Von der Handymarke kommst du zum Model, vom Model kommst du zu einer Auswahlliste von Reperaturdiensleistungen.

    Meilenstein 2
    Nun musst du im letzten Schritt die Select Options durch Input Checkboxen ersetzen. Am besten du platzierst für den Anfang irgendwo ein div mit einer id="auswahl"

    und deine PHP Datei macht dann folgendes

    Quellcode

    1. document.getElementById('auswahl').innerHTML += '<input type="checkbox" name="rep[]" value="hans" /> Hans<br/>';


    Meilenstein 3
    abrunden des ganzen.. div korrekt positionieren, etc
  • Danke, es läuft nun.

    Falls jmd mal mit dem selben Problem zu kämpfen hat, hier meine Lösung:
    index.php

    Quellcode

    1. <script type="text/javascript" src="ajax.js"></script>
    2. <script type="text/javascript">
    3. var ajax = new Array();
    4. function getModelList(sel){
    5. var brand = sel.options[sel.selectedIndex].value;
    6. document.getElementById('model').options.length = 0; // Empty select box
    7. if(brand.length>0){
    8. var index = ajax.length;
    9. ajax[index] = new sack();
    10. ajax[index].requestFile = 'getModels.php?brand='+brand; // Specifying which file to get
    11. ajax[index].onCompletion = function(){ createModels(index) }; // Specify function that will be executed after file has been found
    12. ajax[index].runAJAX(); // Execute AJAX function
    13. }
    14. }
    15. function createModels(index){
    16. var obj = document.getElementById('model');
    17. eval(ajax[index].response); // Executing the response from Ajax as Javascript code
    18. }
    19. function getRepairList(sel){
    20. var model = sel.options[sel.selectedIndex].value;
    21. document.getElementById('repairs').innerHTML = '';
    22. if(model.length>0){
    23. var index = ajax.length;
    24. ajax[index] = new sack();
    25. ajax[index].requestFile = 'getRepairs.php?model='+model; // Specifying which file to get
    26. ajax[index].onCompletion = function(){ createRepairs(index) }; // Specify function that will be executed after file has been found
    27. ajax[index].runAJAX(); // Execute AJAX function
    28. }
    29. }
    30. function createRepairs(index){
    31. var obj = document.getElementById('repairs');
    32. eval(ajax[index].response); // Executing the response from Ajax as Javascript code
    33. }
    34. </script>
    35. <form action="process.php" method="post" name="form" id="form" dir="ltr" lang="de">
    36. <fieldset><legend>Reperaturauftrag</legend>
    37. <p>
    38. <label>Wählen Sie Ihre Marke:</label><br />
    39. <select name="brand" id="brand" size="1" onChange="getModelList(this)" style="width:256px;">
    40. <? include('getBrands.php'); ?>
    41. </select>
    42. </p>
    43. <p>
    44. <label>Wählen Sie Ihr Modell:</label><br />
    45. <select name="model" id="model" size="1" onChange="getRepairList(this)" style="width:256px;">
    46. <? include('getModels.php'); ?>
    47. </select>
    48. </p>
    49. <p id="repairs">Das hier sollte onChange verschwinden!</p>
    50. <p>
    51. <input type="submit" value=" Absenden ">
    52. </p>
    53. </fieldset>
    54. </form>
    Alles anzeigen


    getRepairs.php

    Quellcode

    1. <?php
    2. if(isset($_GET['model'])){
    3. include('db_config.php');
    4. if (mysqli_connect_errno() == 0){
    5. $sql = 'SELECT `ID`, `modelID`, `name` FROM `repairs` WHERE modelID="'.$_GET['model'].'" ORDER BY `ID` DESC';
    6. $result = $db->query( $sql );
    7. while ($row = $result->fetch_object()){
    8. echo "obj.innerHTML += '<input type=\"checkbox\" value=\"".$row->ID."\" /> ".$row->name."<br />';\n";
    9. }
    10. $result->close();
    11. }
    12. else
    13. {
    14. echo 'Die Datenbank konnte nicht erreicht werden. Folgender Fehler trat auf: <strong>'.mysqli_connect_errno().' : '.mysqli_connect_error().'</strong>';
    15. }
    16. $db->close();
    17. }
    18. ?>
    Alles anzeigen


    ajax.js, getModels.php, getBrands.php aus vorigem Post übernehmen.

    Danke nochmal an d0nut.