Home > database >  Google Apps Script web app: How to require at least one checkbox to be checked?
Google Apps Script web app: How to require at least one checkbox to be checked?

Time:06-18

I see a number of questions about "require at least one checkbox to be selected", but none for web apps developed in Google Apps Script.

In a Google Apps Script web app, I can easily require a radio button to be checked with:

<form id="requestNewKeys" onsubmit="handleFormSubmit(this)">
    <p>
        <label for="primaryToolRadioGroup">What is your primary purpose for requesting Tool XXXXXX</label>
    </p>
    <div role="radiogroup" id="primaryPurposeRadioGroup">
        <input type="radio" id="primaryPurpose0" name="primaryPurpose" value="Research" required="">
        <label for="primaryPurpose0">Research</label><br>
        <input type="radio" id="primaryPurpose1" name="primaryPurpose" value="Teaching" required="">
        <label for="primaryPurpose1">Teaching</label><br>
    </div>
    <input type="submit" value="Request License">
</form>

And the handleFormSubmit function:

function handleFormSubmit(formObject) {
    google.script.run.withSuccessHandler(updateResults).processForm(formObject);
}

But I can't figure out the equivalent to require one or more input type="checkbox"s to be checked. I know that Google Apps Script is highly similar to Javascript, but it seems that it's just enough different in this case to make the other solutions I'm finding here not work.

CodePudding user response:

You can try this approach where it only proceeds to the apps script processing if the number of checkboxes ticked is at least 1.

<!DOCTYPE html>
<html>
  <body>
    <form id="requestNewKeys">
      <p>
        <label for="primaryToolCheckboxGroup">What is your primary purpose for requesting Tool XXXXXX</label>
      </p>
      <div role="checkboxgroup" id="primaryPurposeCheckboxGroup">
        <input type="checkbox" id="primaryPurpose0" name="primaryPurpose" value="Research">
        <label for="primaryPurpose0">Research</label><br>
        <input type="checkbox" id="primaryPurpose1" name="primaryPurpose" value="Teaching">
        <label for="primaryPurpose1">Teaching</label><br>
      </div>
      <input type="button" value="Request License" onclick="checkForm()">
    </form>
  </body>
  <script>
    function checkForm() {
      var checkboxes = document.getElementsByName('primaryPurpose');
      var form = document.getElementById('requestNewKeys');
      var checked = 0;
      
      checkboxes.forEach(checkbox => { 
        if(checkbox.checked) 
          checked  ; 
      });

      if(checked > 0)
        // google.script.run.withSuccessHandler(updateResults).processForm(form);
      else
        alert('Please check at least one checkbox!');
    }
  </script>
</html>

After clicking Request License:

output

  • Related