Как я могу собрать данные из нескольких HTML-флажков и ввести эти данные в лист Google? - PullRequest
0 голосов
/ 18 марта 2019

Я продолжаю работу над предыдущим проектом: Данные Google Sheet на боковой панели

Теперь я хотел бы получить элементы, которые были проверены на боковой панели, и вернуть эти данныев файл Code.gs и, в конечном итоге, в Google Sheet (см. код ниже).Можете ли вы предложить предложения о том, как это сделать?

Ниже я пытаюсь добавить отмеченные элементы в массив «студентов».Затем я хотел бы, чтобы кнопка «Отправить досрочное освобождение» отправила массив «студентов» в файл Code.gs.Однако я не уверен, как правильно поместить проверенные элементы в массив.

Page.html

> <!DOCTYPE html>
><html>
>  <head>
>     <base target="_top">
>     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
>  </head>
>    <body>
>     <script>
>     function addStudents(studentList){ 
>       $('#rangeResult').text(studentList);
>       
>       document.write(new Date().toLocaleDateString());
>       
>       var students = [];
>       for (var i = 0; i < studentList.length; i++) {
>         document.write('<br><input type="checkbox" name="studentList[i]" id="i" value="i">'+ studentList[i]);
>       }
>       document.write('<br><input type="button" value="Submit Early Release" onclick="google.script.host.close()" />');
>       document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
>     };
>     
>     google.script.run.withSuccessHandler(addStudents).earlyReleaseList();
>     </script>
>   </body>
></html>

Спасибо за помощь!

Обновление

Мадхав, спасибо за ваши предложения.Я адаптировал ваш код в соответствии со своим сценарием, но мне все еще не удается вернуть данные массива в электронную таблицу.В частности, когда я нажимаю кнопку «Отправить досрочное освобождение», боковая панель закрывается, но данные не записываются в указанную ячейку.Не могли бы вы взглянуть?

Page.html

Добавлена ​​еще одна строка "src =" для jquery - не уверен, если это необходимо ???

Добавлена ​​функция «collectNames» для получения проверенных имен и их отправки обратно

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  </head>
  <body>
    <script>
    function addStudents(studentList){ 
      $('#rangeResult').text(studentList);

      document.write(new Date().toLocaleDateString());

      //var students = [];

      for (var i = 0; i < studentList.length; i++) {
        document.write('<br><input type="checkbox" class="special" name='+ studentList[i]+ 'id="i" value="i">'+ studentList[i]);
      }
      document.write('<br><input type="button" value="Submit Early Release" onclick="collectNames()" />');
      document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
    };

    function collectNames(){
      var students = [];
      var checkboxes=document.getElementsByClassName("special");  //get all checkboxes
      for(var i = 0; i < checkboxes.length; i++){
        if(checkboxes[i].checked){
          students.push(checkboxes[i].getAttribute("name")); //if checked then push to array the value
        }
      }
      //now send the finalarray to the destination
      google.script.run.releasedStudents(students);
      google.script.host.close();
    };

    google.script.run.withSuccessHandler(addStudents).earlyReleaseList();
    </script> 
  </body>
</html>

Code.gs

function releasedStudents(values) {  
  var doc = SpreadsheetApp.openById("1OF6Y1CTU9dkIgd1P-nw-5f2lqHSS5cGZytndwzJhw-o");
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var cell = ss.getRange('V20').getValue();
  cell.setValue(values);
}

1 Ответ

0 голосов
/ 18 марта 2019

Если вы хотите поместить проверенные элементы в массив, то первое, что вам нужно убедиться, это то, что каждый флажок содержит значение, которое он представляет в той или иной форме. Ваш код пытается это сделать, но когда вы пишете

document.write('<br><input type="checkbox" name="studentList[i]" id="i" value="i">'+ studentList[i]);

атрибут name каждого флажка всегда один и тот же, поскольку он является константной строкой ("studentList [i]"), а не значением из массива, поэтому его следует заменить на:

document.write('<br><input type="checkbox" class="special"name='+studentList[i]+ ' id="i" value="i">'+ studentList[i]);

Как только мы закончим с вводом, мы сможем собирать значения только из отмеченных флажков. Один из способов сделать это - назначить класс всем флажкам, чтобы впоследствии к ним можно было получить доступ через getElementsByClassName () функция.

После получения атрибут значения только тех флажков должен быть помещен в массив, у которого свойство checked имеет значение true.

Немного другой код, демонстрирующий это:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <button id="clickthis">Click this</button>


</body>
<script>

    var studentList=["nevil","ron","draco","harry"];
    var finalarray=[];

    function runmyfun(){

            var checkboxes=document.getElementsByClassName("special");  //get all checkboxes
        for(var i=0;i<checkboxes.length;i++){
            if(checkboxes[i].checked){

               finalarray.push(checkboxes[i].getAttribute("name"));      //if checked then push to array the value

            }
        }

        //now send the finalarray to the destination
       }


        document.getElementById("clickthis").onclick=function(){

        document.write(new Date().toLocaleDateString());


        for (var i = 0; i < studentList.length; i++) {
        document.write('<br><input type="checkbox" class="special"name='+studentList[i]+ ' id="i" value="i">'+ studentList[i]);   //concat properly
      }
       document.write('<br><input type="button" value="Submit Early Release" onclick="runmyfun()" />');
      document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
     };


    </script>
</html>

Надеюсь, это то, что вы искали, а не что-то еще.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...