Học Ms excelKỹ năng vi tính

Google sheets Apps scipt|Form nhập liệu lựa chọn phụ thuộc – Data Entry Form with Dependent dropdown

Giaoan.link chia sẻ đến các bạn một project về Google sheets Apps scipt, Form nhập liệu lựa chọn phụ thuộc – Data Entry Form with Dependent dropdown. Với chia sẻ này bạn sẽ biết cách tạo cho mình một Form nhập liệu có các trường lựa chọn có phụ thuộc – trường sau phụ thuộc vào trường trước nó. Dữ liệu được lưu trên sheet “Data”, sheet “Dependent” dùng để tạo bản danh sách phụ thuộc.

||Bạn truy cập tại đây để xem và tìm các project về excel và google sheet

Các bài ngẫu nhiên:

Mã trang “Code.gs”

const DATASHEET = "Data";
let MySheets =SpreadsheetApp.getActive();
let CitySheet = MySheets.getSheetByName("Dependent");  

function doGet() {
  var output = HtmlService.createTemplateFromFile('Index');   
  return output.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

//Begin Dropdown
function removeDuplicates(data) {
  console.log(data);
  newArray = [];
  oldData="";
  data.forEach(function(value) {
    value = value[0];
    if (oldData != value)
      newArray.push(value);
    oldData = value;
 });
 return newArray;
}

function getCountryList() {
  let table = CitySheet.getRange("A2:A").getValues().filter(r => r.every(Boolean)); 
  table = removeDuplicates(table);
  return table;
}


function getStateList(Country) {
  let returnData = CitySheet.getRange("A:A").createTextFinder(Country).matchEntireCell(true).findAll();

    newArray = [];
    returnData.forEach(function (range) {
        let value = CitySheet.getRange(range.getRow(), 2).getValue();
        newArray.push([value]);
    });

    newArray = removeDuplicates(newArray);
    return newArray;
}

function getCityList(State) {
    let returnData = CitySheet.getRange("B:B").createTextFinder(State).matchEntireCell(true).findAll();
    newArray = [];
    returnData.forEach(function (range) {
          let value = CitySheet.getRange(range.getRow(), 3).getValue();
          newArray.push([value]);
    });

    newArray = removeDuplicates(newArray);
    return newArray;
}

//End Dependent dropdown

function processForm(formObject) {
  const ss = SpreadsheetApp.getActive();
  const dataSheet = ss.getSheetByName(DATASHEET);
  
  dataSheet.appendRow([
    new Date().toLocaleString(),
    formObject.full_name,
    formObject.phone_number,       
    formObject.idtinh,
    formObject.idhuyen,
    formObject.idxa
  ]);
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

Mã trang “Index.html”

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" />  
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
    </script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"
      integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous">
  </script>   
  </head>

  <body class="text-light" style="background-color: gray" onload="getCountry();">
    <br>
    <div class="container" style="border: solid 2px #aafe7d; background-color: green; border-radius: 10px" >      
      <?!= include('Form'); ?>   
    </div>
    <div style="height: 10px;"></div>
    <div class="text-center"><a style="color: white;text-decoration:none" href="https://giaoan.link" target="_blank"> Giaoan.link<a/> &copy; 2024</center></div>
    <?!= include('JavaScript'); ?>  
  </body>

</html>

Mã trang “Form.html”


<div id="reader-results"></div>
<form id="InventoryForm" onsubmit="handleFormSubmit(this)"> 
  <div style="text-align: center; font-size: 25px; font-weight: bold;">FORM NHẬP LIỆU CÓ LỰA CHỌN CÓ PHỤ THUỘC <br>
  <span style="font-size: 20px; font-style: italic">Đáp ứng với nhiều loại màn hình - Responsive</span>
  </div>
  
  <div style="height: 5px;"></div>
      <div class="mb-3 input-group">
        <span class="input-group-text bg-primary text-white"><i class="bi bi-people-fill"></i></span>
        <input type="text" class="form-control" id="full_name" name="full_name" placeholder="Họ và tên" required>
      </div>

      <div class="mb-3 input-group">
        <span class="input-group-text bg-primary text-white"><i class="bi bi-telephone-fill"></i></span>
        <input type="number" class="form-control" id="phone_number" name="phone_number" placeholder="Số điện thoại" required>
      </div>
  
      <div class="col-md-20 mb-2">                    
          <div class="input-group">
            <span class="input-group-text bg-primary text-white"><i class="bi bi-list-check"></i></span>
            <select class="form-control ClsCountry"  id="idtinh" name="idtinh" autocomplete="off" onchange="getState(this.value)">
            <option>Chọn tỉnh...</option>
            </select>
          </div>           
        </div>   

      <div class="col-md-20 mb-2">                    
        <div class="input-group">
          <span class="input-group-text bg-primary text-white"><i class="bi bi-list-stars"></i></span>
          <select class="form-control ClsState"  id="idhuyen" name="idhuyen" autocomplete="off"  onchange="getCity(this.value)" required>
          <option>Lựa chọn...</option>
          </select>
        </div>           
      </div>

      <div class="col-md-20 mb-2">                    
          <div class="input-group">
            <span class="input-group-text bg-primary text-white"><i class="bi bi-option"></i></span>
            <select class="form-control ClsCity" id="idxa" name="idxa" autocomplete="off" required>
            <option>Lựa chọn...</option>
            </select>
          </div>           
        </div>  
      
  <div style="height: 5px;"></div>
  <button type="submit" class="btn btn-warning mb-3 w-100 fw-bold">Submit</button>
</form>
  

Mã trang “JavaScript.html”

<script>
  window.addEventListener("load", functionInit, true); 

  //Initialize functions onload
  function functionInit(){
    preventFormSubmit();
  };

  // Prevent forms default behaviour (Prevent reloading the page)
  function preventFormSubmit() {
    var forms = document.querySelectorAll('form');
    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function(event) {
      event.preventDefault();
      });
    }
  } 

  /**
   * The handleFormSubmit() function passes the formObject to the processForm 
   * function in the Code.gs file
   */
  function handleFormSubmit(formObject) {
    // Get the Data from the div
    google.script.run.processForm(formObject);
    const resultContainer = document.getElementById('reader-results');
    resultContainer.innerHTML = '';
    document.getElementById("InventoryForm").reset();
  }
 
  function getCountry() {
    google.script.run.withSuccessHandler(function(data) {
        var Options="";                              
        $.each(data, function(key, value)            
        {
            Options = Options + '<option>' + value + '</option>';   
        });
        $(".ClsCountry").append(Options);           
    }).getCountryList();
  }

  function getState(Country) {
    
    google.script.run.withSuccessHandler(function(data) {
        var Options="";                              
        $.each(data, function(key, value)            
        {
            Options = Options + '<option>' + value + '</option>';  
        });
        $(".ClsState").empty().append('<option>Chọn huyện...</option>');
        $(".ClsState").append(Options);           
    }).getStateList(Country);
  }
  

  function getCity(State) {
    
    google.script.run.withSuccessHandler(function(data) {
        var Options="";                              
        $.each(data, function(key, value)            
        {
            Options = Options + '<option>' + value + '</option>';   
        });
        $(".ClsCity").empty().append('<option>Chọn xã...</option>');
        $(".ClsCity").append(Options);           
    }).getCityList(State);
  }  

</script>





giaoanppt

Giaoan.link trang chia sẽ giáo án điện tử, bài giảng powerpoint, template powerpoint, nguyên liệu làm bài giảng, tài liệu, biểu mẫu miễn phí!

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

This site uses Akismet to reduce spam. Learn how your comment data is processed.