0

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

arul selvan
  • 616
  • 4
  • 17
  • When I saw your sample Spreadsheet, the script in the sample Spreadsheet is different from your question. And, when I saw your HTML in your question, it is different from your sample image. So I cannot understand about your current situation. I apologize for this. In order to correctly understand about your question, can you provide your latest script and samples for replicating your issue? And also, can you provide the detail of your current issue of your script and your goal? By this, I would like to try to understand your question. – Tanaike Apr 12 '21 at 05:36
  • Sorry, Please ignore the script in the sheet. I deleted it. What I want is - when I select a company (C1 or C2 or C3), the next drop down products must change as per company selected ( if company selected is C1 product drop down must have C1P1, C1P2,C1P3 and if company selected is C2 products drop down must be C2P1,C2P2 ) – arul selvan Apr 12 '21 at 05:54
  • It will be more user friendly if the company names and product names will get populated from the "Company" Sheet automatically – arul selvan Apr 12 '21 at 05:56
  • https://script.google.com/home/projects/1NFSyN2ST5LeC-iqLZALFPHMmX7iJ8LWpuU24l4TwBvkQTVTcBQlzEwM4/edit – arul selvan Apr 12 '21 at 06:01
  • that's my latest script (with edit rights) – arul selvan Apr 12 '21 at 06:01
  • I referred to http://jsfiddle.net/k148pk76/1/ for making this script – arul selvan Apr 12 '21 at 06:02
  • I also referred to https://stackoverflow.com/questions/30232146/dynamically-populating-drop-down-list-from-selection-of-another-drop-down-value – arul selvan Apr 12 '21 at 06:18
  • Thank you for your additional information. When I saw your latest script, I think that your script is not complete. For example, I cannot find the function of `showPosition` and the value of `companyId`. Are these related to your current issue? From this situation, unfortunately, I cannot still understand about your current issue. I apologize for this. Can I ask you about the detail of your current issue? – Tanaike Apr 12 '21 at 06:26
  • @Tanaike - Pl. help, I'm stuck – arul selvan Apr 12 '21 at 07:36
  • @Tanaike I copied the code from the jsfiddle and it worked without any problem. Then I changed the label names and I could complete the project. Thanks for always being there to help – arul selvan Apr 12 '21 at 08:34

1 Answers1

0

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/

Ortund
  • 8,095
  • 18
  • 71
  • 139
  • Don't forget to add some kind of value to your `options` before adding them to the list otherwise your backend won't know which one was selected. – Ortund Apr 12 '21 at 06:28
  • - Thanks. I tried your suggestions in my script. I am not successful. Will be helpful, if you can modify my code (not jsfiddle code). I am not able to understand the mistake I am making – arul selvan Apr 12 '21 at 07:35
  • @arulselvan it's the same problem I indicated. In your for loop in `index.html` you need to change `companyOptions += "";` to `companyOptions += "";` – Ortund Apr 12 '21 at 09:33