-3

How can I get the values and save into the database my dependent dropdown list array which is to be displayed using innerHTML? The database is only saving the last chosen values and not all the selected values. I know that my problem would be printing the last values directly into the table cell that is why Im not getting all the chosen values. How can I save all the values of these multiple dropdown list that are chosen by the user after being displayed into my table?

window.onload = function() {
  var ModelArray = {
    "Mammals": {
      "Dog": {
        "Dog Food": ["Milk"]
      },
      "Cat": {
        "Cat food": ["Milk"]
      },
      "Tiger": {
        "Meat": ["Water"]
      },
      "Monkey": {
        "Banana": ["Water"]
      }
    },
    "Reptiles": {
      "Snake": {
        "Rat": ["None"]
      },
      "Turtle": {
        "Plant": ["Water"]
      },
      "Lizard": {
        "Insects": ["None"]
      },
      "Crocodile": {
        "Meat": ["Water"]
      }
    }
  }


  //Get html elements
  var model = document.getElementById("MODEL");
  var destination = document.getElementById("destination");
  var criteria = document.getElementById("criteria");
  var material_form = document.getElementById("material_form");

  //load models
  for (var model_value in ModelArray) {
    model.options[model.options.length] = new Option(model_value, model_value);
  }

  //model changed -> destination value
  model.onchange = function() {

    destination.length = 1;
    criteria.length = 1;
    material_form.length = 1;

    if (this.selectedIndex < 1) {
      criteria.options[0].text = ""
      return;
    }
    destination.options[0].text = "Select Animal..."
    for (var destination_value in ModelArray[this.value]) {
      destination.options[destination.options.length] = new Option(destination_value, destination_value);
    }
    if (destination.options.length == 2) {
      destination.selectedIndex = 1;
      destination.onchange();
    }
  }

  //destination changed -> criteria value
  model.onchange();
  destination.onchange = function() {

    criteria.length = 1;
    material_form.length = 1;

    if (this.selectedIndex < 1) {
      criteria.options[0].text = ""
      return;
    }
    criteria.options[0].text = ""
    for (var criteria_value in ModelArray[model.value][this.value]) {
      criteria.options[criteria.options.length] = new Option(criteria_value, criteria_value);
    }
    if (criteria.options.length == 2) {
      criteria.selectedIndex = 1;
      criteria.onchange();
    }
  }

  //criteria changed -> material form value
  criteria.onchange = function() {
    material_form.length = 1;

    if (this.selectedIndex < 1) {
      material_form.options[0].text = ""
      return;
    }
    material_form.options[0].text = ""
    var material_form_value = ModelArray[model.value][destination.value][this.value];

    for (var i = 0; i < material_form_value.length; i++) {
      material_form.options[material_form.options.length] = new Option(material_form_value[i], material_form_value[i]);
    }
    if (material_form.options.length == 2) {
      material_form.selectedIndex = 1;
      // material_form.onchange();
    }
  }
}


function addRow() {
  var table = document.getElementById("myTableData");
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);


  row.insertCell(0).innerHTML = destination.value;
  row.insertCell(1).innerHTML = criteria.value;
  row.insertCell(2).innerHTML = material_form.value;
  row.insertCell(3).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)">';
}

function deleteRow(obj) {

  var index = obj.parentNode.parentNode.rowIndex;
  var table = document.getElementById("myTableData");
  table.deleteRow(index);

}
<td><b>MODEL: </b></td>
<td>
  <select id="MODEL" NAME="MODEL" size="1" required>
    <option value="" selected="selected">Select Model...</option>
  </select>
</td>
<b>DESTINATION: </b></td>
<tr>
  <td>
    <select ID="destination" NAME="destination[]" required>
      <option value="" selected="selected">Select Model First...</option>
    </select>
    <select ID="criteria" NAME="criteria[]" contenteditable="true" style="display: none" required>
    </select>
    <select id="material_form" name="material_form[]" style="display: none" required>
    </select>
    <input type="button" id="add" value="Add Destination" onclick="Javascript:addRow()">
  </td>
</tr>
<div id="mydata" style="text-align: center">
  <table id="myTableData">
    <tr>
      <td style="text-align:center;"><b>DESTINATION</b></td>
      <td style="text-align:center;"><b>CRITERIA</b></td>
      <td style="text-align:center;"><b>MATERIAL FORM</b></td>
    </tr>
    
    
 
<!---- 
 
  <?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'mydatabase';

$dbconn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db);
 
 $dynamic_textbox_count = count($_POST["destination"]);
    $dynamic_textbox_value=0;
    $query = "INSERT INTO dynamic_values (destination, criteria, material_form) VALUES ";
    $queryValue = "";
        for($i=0;$i<$dynamic_textbox_count;$i++) {
            if(!empty($_POST["destination"][$i]) || !empty($_POST["criteria"][$i]) || !empty($_POST["material_form"][$i])) {
                $dynamic_textbox_value++;
                if($queryValue!="") {
                    $queryValue .= ",";
                }
                $queryValue .= "('" . $_POST["destination"][$i] . "', '" . $_POST["criteria"][$i] . "', '" . $_POST["material_form"][$i] . "')";
            }
        }
        $sql = $query.$queryValue;
        if($dynamic_textbox_value!=0) {
            $result = mysql_query($sql);
            if(!empty($result)) $message = "Added Successfully.";
        }
    mysql_close();
?>

-->

1 Answers1

0

something like this ? use jquery.

window.onload = function() {
      var ModelArray = {
        "Mammals": {
          "Dog": {
            "Dog Food": ["Milk"]
          },
          "Cat": {
            "Cat food": ["Milk"]
          },
          "Tiger": {
            "Meat": ["Water"]
          },
          "Monkey": {
            "Banana": ["Water"]
          }
        },
        "Reptiles": {
          "Snake": {
            "Rat": ["None"]
          },
          "Turtle": {
            "Plant": ["Water"]
          },
          "Lizard": {
            "Insects": ["None"]
          },
          "Crocodile": {
            "Meat": ["Water"]
          }
        }
      }


      //Get html elements
      var model = document.getElementById("MODEL");
      var destination = document.getElementById("destination");
      var criteria = document.getElementById("criteria");
      var material_form = document.getElementById("material_form");

      //load models
      for (var model_value in ModelArray) {
        model.options[model.options.length] = new Option(model_value, model_value);
      }

      //model changed -> destination value
      model.onchange = function() {

        destination.length = 1;
        criteria.length = 1;
        material_form.length = 1;

        if (this.selectedIndex < 1) {
          criteria.options[0].text = ""
          return;
        }
        destination.options[0].text = "Select Animal..."
        for (var destination_value in ModelArray[this.value]) {
          destination.options[destination.options.length] = new Option(destination_value, destination_value);
        }
        if (destination.options.length == 2) {
          destination.selectedIndex = 1;
          destination.onchange();
        }
      }

      //destination changed -> criteria value
      model.onchange();
      destination.onchange = function() {

        criteria.length = 1;
        material_form.length = 1;

        if (this.selectedIndex < 1) {
          criteria.options[0].text = ""
          return;
        }
        criteria.options[0].text = ""
        for (var criteria_value in ModelArray[model.value][this.value]) {
          criteria.options[criteria.options.length] = new Option(criteria_value, criteria_value);
        }
        if (criteria.options.length == 2) {
          criteria.selectedIndex = 1;
          criteria.onchange();
        }
      }

      //criteria changed -> material form value
      criteria.onchange = function() {
        material_form.length = 1;

        if (this.selectedIndex < 1) {
          material_form.options[0].text = ""
          return;
        }
        material_form.options[0].text = ""
        var material_form_value = ModelArray[model.value][destination.value][this.value];

        for (var i = 0; i < material_form_value.length; i++) {
          material_form.options[material_form.options.length] = new Option(material_form_value[i], material_form_value[i]);
        }
        if (material_form.options.length == 2) {
          material_form.selectedIndex = 1;
          // material_form.onchange();
        }
      }
    }
    function addRow() {
      var table = document.getElementById("bod");
      var rowCount = table.rows.length;
      var row = table.insertRow(rowCount);


      row.insertCell(0).innerHTML = destination.value;
      row.insertCell(1).innerHTML = criteria.value;
      row.insertCell(2).innerHTML = material_form.value;
      row.insertCell(3).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)">';
    }
    function deleteRow(obj) {
      var index = obj.parentNode.parentNode.rowIndex;
      var table = document.getElementById("myTableData");
      table.deleteRow(index);
    }
    //Get Tabel Data 
    $('#tabdata').on('click',function(){
      var TableData=new Array();
      $('#myTableData tbody tr').each(function(row, tr){
          TableData[row]={
              "dest" :$(tr).find('td:eq(0)').text(),
              "crit" :$(tr).find('td:eq(1)').text(),
              "mat" :$(tr).find('td:eq(2)').text(),
          }
      });
      console.log(TableData);
      $.ajax({
            url: 'http://example.com' //Your Url for receive data,
            type: 'POST',
            dataType: 'json',
            data: {pet:TableData},
            success : function(data){
              console.log(data);//On Success receive callback
            },
            error: function(xhr, ajaxOptions, thrownError){
              console.log(thrownError);//If php return error, showing here
            }
          });
    });
<td><b>MODEL: </b></td>
    <td>
      <select id="MODEL" NAME="MODEL" size="1" required>
        <option value="" selected="selected">Select Model...</option>
      </select>
    </td>
    <b>DESTINATION: </b></td>
    <tr>
      <td>
        <select ID="destination" NAME="destination[]" required>
          <option value="" selected="selected">Select Model First...</option>
        </select>
        <select ID="criteria" NAME="criteria[]" contenteditable="true" style="display: none" required>
        </select>
        <select id="material_form" name="material_form[]" style="display: none" required>
        </select>
        <input type="button" id="add" value="Add Destination" onclick="Javascript:addRow()">
      </td>
    </tr>
    <div id="mydata" style="text-align: center">
      <table id="myTableData">
        <thead>
          <tr>
            <td style="text-align:center;"><b>DESTINATION</b></td>
            <td style="text-align:center;"><b>CRITERIA</b></td>
            <td style="text-align:center;"><b>MATERIAL FORM</b></td>
          </tr>
        </thead>
        <tbody id="bod">
        </tbody>
      </table>
    </div>
    <button id="tabdata">Get Data</button>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

On PHP (serverside)

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'mydatabase';

$dbconn =mysqli_connect($dbhost,$dbuser,$dbpass,$db);
function insert($destination,$criteria,$material_form){
    $query=$dbconn->query("INSERT INTO dynamic_values (destination, criteria, material_form) VALUES('$destination','$criteria','$material_form')");
}
$destidata=json_decode($_POST["pet"]);
foreach ($destidata as $key) {
    insert($key->dest,$key->crit,$key->mat);
}
?>
Thomas Jeriko
  • 213
  • 3
  • 13