0

So, I am currently making a website where the user will fill out his information and then have to select various checkboxes to let the admin know what all services he/she require, Now I am able to retrieve the simple information like Name, email, phone number and can successfully send it to the admin's email but there's a problem the sheet shows "on" even for the checkboxes that were not selected. I am not able to solve this problem, I want to show only that data with that specific user that he selected only and not the ones that he/she didn't select.

Here is my html Form:-

 <div class="form-group col-md-6">
                           <div id="list1" class="dropdown-check-list" tabindex="100">
                              <span class="anchor" name="programs">Select Programs</span>
                              <form action="https://script.google.com/macros/s/AKfycbxL1JOIFNoOLyqaiQFaOM-b70ceKnRRScc1yCm7zW4wsf_15CrJcx_3/exec">
                                 <ul class="items">
                                    <li><input type="checkbox" class="form-control" name="tracheostomy-care" />Tracheostomy Care </li>
                                    <li><input type="checkbox" class="form-control" name="post-stroke-care" />Post-Stroke Care</li>
                                    <li><input type="checkbox" class="form-control" name="feeding-tube-care" />Feeding Tube Care </li>
                                    <li><input type="checkbox" class="form-control" name="bedsore-management" />Bed Sore Management </li>
                                    <li><input type="checkbox" class="form-control" name="speech-therapy" />Speech Therapy </li>
                                    <li><input type="checkbox" class="form-control" name="catheter-care" />Catheter Care</li>
                                    <li><input type="checkbox" class="form-control" name="cardiac-care" />Cardiac Care</li>
                                    <li><input type="checkbox" class="form-control" name="parkinsons-care" />Parkinsons Care</li>
                                    <li><input type="checkbox" class="form-control" name="craniotomy-care" />Craniotomy Care</li>
                                    <li><input type="checkbox" class="form-control" name="pulmonary-care" />Pulmonary Care</li>
                                    <li><input type="checkbox" class="form-control" name="orthopaedic-care"/>Orthopaedic Care</li>
                                 </ul>
                              </form>   

And this is my google 'script.gs':-

// if you want to store your email server-side (hidden), uncomment the next line
 var TO_ADDRESS = "bhattanugrah07@gmail.com";

// spit out all the keys/values from the form in HTML for email
// uses an array of keys if provided or the object to determine field order
function formatMailBody(obj, order) {
  var result = "";
  if (!order) {
    order = Object.keys(obj);
  }
  
  // loop over all keys in the ordered form data
  for (var idx in order) {
    var key = order[idx];
    result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + sanitizeInput(obj[key]) + "</div>";
    // for every key, concatenate an `<h4 />`/`<div />` pairing of the key name and its value, 
    // and append it to the `result` string created at the start.
  }
  return result; // once the looping is done, `result` will be one long string to put in the email body
}

// sanitize content from the user - trust no one 
// ref: https://developers.google.com/apps-script/reference/html/html-output#appendUntrusted(String)
function sanitizeInput(rawInput) {
   var placeholder = HtmlService.createHtmlOutput(" ");
   placeholder.appendUntrusted(rawInput);
  
   return placeholder.getContent();
 }

function doPost(e) {

  try {
    Logger.log(e); // the Google Script version of console.log see: Class Logger
    record_data(e);
    
    // shorter name for form data
    var mailData = e.parameters;

    // names and order of form elements (if set)
    var orderParameter = e.parameters.formDataNameOrder;
    var dataOrder;
    if (orderParameter) {
      dataOrder = JSON.parse(orderParameter);
    }
    
    // determine recepient of the email
    // if you have your email uncommented above, it uses that `TO_ADDRESS`
    // otherwise, it defaults to the email provided by the form's data attribute
    var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
    
    // send email if to address is set
    if (sendEmailTo) {
      MailApp.sendEmail({
        to: String(sendEmailTo),
        subject: "Contact form submitted",
        // replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
        htmlBody: formatMailBody(mailData, dataOrder)
      });
    }

    return ContentService    // return json success results
          .createTextOutput(
            JSON.stringify({"result":"success",
                            "data": JSON.stringify(e.parameters) }))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(error) { // if error return this
    Logger.log(error);
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": error}))
          .setMimeType(ContentService.MimeType.JSON);
  }
}


/**
 * record_data inserts the data received from the html form submission
 * e is the data received from the POST
 */
function record_data(e) {
  var lock = LockService.getDocumentLock();
  lock.waitLock(30000); // hold off up to 30 sec to avoid concurrent writing
  
  try {
    Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it
    
    // select the 'responses' sheet by default
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    var sheetName = e.parameters.formGoogleSheetName || "responses";
    var sheet = doc.getSheetByName(sheetName);
    
    var oldHeader = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var newHeader = oldHeader.slice();
    var fieldsFromForm = getDataColumns(e.parameters);
    var row = [new Date()]; // first element in the row should always be a timestamp
    
    // loop through the header columns
    for (var i = 1; i < oldHeader.length; i++) { // start at 1 to avoid Timestamp column
      var field = oldHeader[i];
      var output = getFieldFromData(field, e.parameters);
      row.push(output);
      
      // mark as stored by removing from form fields
      var formIndex = fieldsFromForm.indexOf(field);
      if (formIndex > -1) {
        fieldsFromForm.splice(formIndex, 1);
      }
    }
    
    // set any new fields in our form
    for (var i = 0; i < fieldsFromForm.length; i++) {
      var field = fieldsFromForm[i];
      var output = getFieldFromData(field, e.parameters);
      row.push(output);
      newHeader.push(field);
    }
    
    // more efficient to set values as [][] array than individually
    var nextRow = sheet.getLastRow() + 1; // get next row
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);

    // update header row with any new data
    if (newHeader.length > oldHeader.length) {
      sheet.getRange(1, 1, 1, newHeader.length).setValues([newHeader]);
    }
  }
  catch(error) {
    Logger.log(error);
  }
  finally {
    lock.releaseLock();
    return;
  }

}

function getDataColumns(data) {
  return Object.keys(data).filter(function(column) {
    return !(column === 'formDataNameOrder' || column === 'formGoogleSheetName' || column === 'formGoogleSendEmail' || column === 'honeypot');
  });
}

function getFieldFromData(field, data) {
  var values = data[field] || '';
  var output = values.join ? values.join(', ') : values;
  return output;
}
Anugrah Bhatt
  • 33
  • 1
  • 5
  • Does this answer your question? [Get selected value in dropdown list using JavaScript](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – ale13 Mar 05 '21 at 13:18

1 Answers1

0

What if you use something like this...

<div class="form-group col-md-6">
  <div class="dropdown-check-list" tabindex="100">
    <span class="anchor" name="programs">Select Programs</span>
    <form action="https://script.google.com/macros/s/AKfycbxL1JOIFNoOLyqaiQFaOM-b70ceKnRRScc1yCm7zW4wsf_15CrJcx_3/exec">
        <select class="items" id="list1">
          <option class="form-control" name="tracheostomy-care" />Tracheostomy Care </option>
          <option class="form-control" name="post-stroke-care" />Post-Stroke Care</option>
          <option class="form-control" name="feeding-tube-care" />Feeding Tube Care </option>
          <option class="form-control" name="bedsore-management" />Bed Sore Management </option>
          <option class="form-control" name="speech-therapy" />Speech Therapy </option>
          <option class="form-control" name="catheter-care" />Catheter Care</option>
          <option class="form-control" name="cardiac-care" />Cardiac Care</option>
          <option class="form-control" name="parkinsons-care" />Parkinsons Care</option>
          <option class="form-control" name="craniotomy-care" />Craniotomy Care</option>
          <option class="form-control" name="pulmonary-care" />Pulmonary Care</option>
          <option class="form-control" name="orthopaedic-care"/>Orthopaedic Care</option>
        </select>
    </form>  

Check these out:

Get selected value in dropdown list using JavaScript

Get the value of checked checkbox?

James VB
  • 93
  • 7
  • Hey, thank you for these, I'll definitely check them out, Can you also help me with one thing? Can you tell me how to change the "value" attribute of the checkbox if checked because i've noticed that the value attribute is sent to the google sheet irrespective of if they are checked or not, So I plan to change the value of those checkboxes those that are selected so that i can differ them from those unchecked. – Anugrah Bhatt Mar 05 '21 at 08:24
  • Something like `
  • Tracheostomy Care
  • ` might work. [link](https://www.w3schools.com/jsref/met_element_setattribute.asp) & [link](https://www.w3schools.com/jsref/dom_obj_event.asp) – James VB Mar 05 '21 at 18:45