简体   繁体   English

如何在 Google Apps 脚本中获取复选框的值

[英]how to get value of checkbox in Google Apps script

I have created a checkbox in Google sheet sidebar which has a form with a checkbox field.我在 Google 工作表侧边栏中创建了一个复选框,它有一个带有复选框字段的表单。

Regardless of whether i check the checkbox or not, i get the value as "on".无论我是否选中复选框,我都会得到“on”的值。

I need to know whether the checkbox was checked or not我需要知道复选框是否被选中

    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

            <form>
    <div>
    <p>
          <label>
            <input name="item" id="Agree" type="checkbox" class="red"/>
            <span>Agree</span>

          </label>
        </p>
        </div>

            <div class="input-field col s12">

            <button class="btn waves-effect waves-light" type="submit" name="action" id="btn">Generate
        <i class="material-icons right">send</i>
      </button>

        </div>
        </form>

       <script>

                var agreeValue = document.getElementById("Agree")


                document.getElementById("btn").addEventListener("click", addRecord);

                function addRecord() {
                var data = {
                agreeValue               : Agree.value
                };


                google.script.run.appendData(data);
                }





    </script>

  </body>
</html>

If you want to confirm the checkbox by on and off , how about modifying as follows?如果你想通过onoff来确认复选框,那么修改如下如何?

From:从:

var data = {
  agreeValue: Agree.value
};

To:到:

var data = {
  agreeValue: agreeValue.checked ? "on" : "off" // or Agree.checked ? "on" : "off"
};
  • By this modification, when the checkbox is checked and unchecked, data becomes {agreeValue: "on"} and {agreeValue: "off"} , respectively.通过这种修改,当复选框被选中和取消选中时, data变为{agreeValue: "on"}{agreeValue: "off"}

Note:笔记:

  • When var data = {agreeValue: agreeValue.checked} is used, you can retrieve the value of checkbox as a boolean.当使用var data = {agreeValue: agreeValue.checked} ,您可以检索复选框的值作为布尔值。

If I misunderstood your question and this was not the result you want, I apologize.如果我误解了您的问题并且这不是您想要的结果,我深表歉意。

In your HTML file enter code like this.在您的 HTML 文件中输入这样的代码。 The checkbox is now a Boolean复选框现在是布尔值

function addRecord() {
                var data = document.getElementsById("agree")[0].checked;

                google.script.run.appendData(data);
}

Then in the server side script place the data parameter in the condition of the If statement like this, since the condition of a if statement is in essence a boolean which you are pulling from you're html checkbox input.然后在服务器端脚本中,将data参数放在这样的 If 语句的条件中,因为 if 语句的条件本质上是一个布尔值,您从 html 复选框输入中提取该布尔值。

if (data) {
   //code to execute if checkbox is checked
} else {
   //code to execute if NOT checked
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM