Dependent Dropdown in HTML form

1.9k Views Asked by At

I need a dependent dropdown in my HTML form.

I referred http://jsfiddle.net/k148pk76/1/ to make the below code.

The "dependent" dropdown is not getting populated.

Code.gs

function doGet(request) {
  return HtmlService.createTemplateFromFile('Index').evaluate();
}

/* @Include JavaScript and CSS Files */
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
  .getContent();
}

/* @Process Form */
function processForm(formObject) {
  var url = "https://docs.google.com/spreadsheets/d/1fCCi2-dvA9K_pxlOkO3BSLkUDPiphVtu2gkNp4_zQR4/edit#gid=284578578";
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Survey");
  ws.appendRow(
    [
      new Date(),
      formObject.surveyor,
      formObject.company,
      formObject.product,
      formObject.rating,
      formObject.rem,
    ]
  );
}

Index.html

<!DOCTYPE html>
<html>

<head>
    <base target="_top">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <?!= include('JavaScript'); ?>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-6">
                <form id="myForm" onsubmit="handleFormSubmit(this);">
                    <p class="h4 mb-4 text-left">Product satisfaction Survey</p>


                    <div class="form-group">
                        <label for="Surveyor">Surveyor (Select one)</label>
                        <select class="form-control" id="surveyor" name="surveyor" required>
                            <option selected disabled hidden style='display: none' value=''></option>
                            <option value="S1">S1</option>
                            <option value="S2">S2</option>
                            <option value="S3">S3</option>
                            <option value="S4">S4</option>
                        </select>
                    </div>


                    <div class="form-group">
                      <label for="company">company (Select one)</label>
                      <select name="company" id="company" onChange="changeCompany(this.value);">    <option value="" disabled selected>Select</option>
                        <option value="C1">C1</option>
                        <option value="C2">C2</option>
                        <option value="C3">C3</option>
                      </select>
                    </div>

                    <div class="form-group">
                      <label for="product">product (Select one)</label>
                      
                      <select name="product" id="product">
                      <option value="" disabled selected>Select</option>
                      </select>
                    </div>


                    <div class="form-group">
                        <label for="Rating">Rating (Select one)</label>
                        <select class="form-control" id="rating" name="rating" required>
                            <option selected disabled hidden style='display: none' value=''></option>
                            <option value="1">1. Not Interested</option>
                            <option value="2">2. Minor Interest - Needs Some Changes</option>
                            <option value="3">3. Neutral</option>
                            <option value="4">4. Interested - Not a Major Priority. Work in When Appropriate</option>
                            <option value="5">5. Extremely Interested - Put into Testing Process</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="rem">Remark</label>
                        <input type="text" class="form-control" id="rem" name="rem">
                    </div>


                    <div class="form-group">
                        <input type="hidden" class="form-control" id="lat" name="lat">
                        <input type="hidden" class="form-control" id="long" name="long">
                    </div>

                    <button type="submit" class="btn btn-primary btn-block">Submit</button>
                </form>

                <div id="output"></div>
            </div>
        </div>
    </div>
</body>

</html>



<script>

  var productsByCompany = {
    C1: ["C1P1", "C1P2", "C1P3"],
    C2: ["C2P1", "C2P2"],
    C3: ["C3P1", "C3P2", "C3P3","C4P4"]
}

    function changeCompany(value) {
        if (value.length == 0) document.getElementById("company").innerHTML = "<option></option>";
        else {
            var companyOptions = "";
            for (comanyId in productsByCompany[value]) {
                companyOptions += "<option>" + productsByCompany[value][categoryId] + "</option>";
            }
            document.getElementById("company").innerHTML = companyOptions;
        }
    }

</script>


JavaScript.html

<script>
    // Prevent forms from submitting.
    function preventFormSubmit() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i++) {
            forms[i].addEventListener('submit', function(event) {
                event.preventDefault();
            });
        }
    }
    window.addEventListener('load', preventFormSubmit);
    window.addEventListener('load', showPosition);

    function handleFormSubmit(formObject) {
        google.script.run.processForm(formObject);
        document.getElementById("myForm").reset();
        //var formvals = Objapp.objectToArray(formObject); 
        alert('Your response was saved successfully');
    }
</script>

All the values (other than the "dependent" drop down) are getting populated in the sheet

https://docs.google.com/spreadsheets/d/1fCCi2-dvA9K_pxlOkO3BSLkUDPiphVtu2gkNp4_zQR4/edit#gid=1993914568

by the webapp

https://script.google.com/macros/s/AKfycbxlrXrGzNvLvJQy4kbH1XxjM0tlCas7Bj2ycJmL0G5AcZhlepx2njoa4irA9J76mWD5/exec

This is the branching google form I tried. But, it requires 300 branches and creates 600 columns, which I don't want.

enter image description here

1

There are 1 best solutions below

3
Ortund On

Your jsfiddle was a little off. There's no need to reference the selected array item in the for loop when changing the dropdown items.

So your initial for loop:

for (categoryId in mealsByCategory[value]) {
  catOptions += "<option>" + mealsByCategory[value][categoryId] + "</option>";
}

Changes to this:

for (categoryId of mealsByCategory[value]) {
  catOptions += "<option>" + categoryId + "</option>";
}

Remember that we already know which meal category we're looking at because it's declared as the collection through which we're looping.

var mealsByCategory = {
  A: ["Soup", "Juice", "Tea", "Others"],
  B: ["Soup", "Juice", "Water", "Others"],
  C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
}

function changecat(value) {
  // Clear the target dropdown so that we don't stack results.
  const categoryList = document.querySelector("#category");
  categoryList.innerHTML = "";
  
  if (value.length == 0)
  {
    categoryList.innerHTML = "<option></option>";
  }
  else {
    let catOptions = "";
    for (categoryId of mealsByCategory[value]) {
      catOptions += "<option>" + categoryId + "</option>";
    }
    categoryList.innerHTML = catOptions;
  }
}
<select name="meal" id="meal" onChange="changecat(this.value);">
    <option value="" disabled selected>Select</option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>
<select name="category" id="category">
    <option value="" disabled selected>Select</option>
</select>

http://jsfiddle.net/j3p7f642/