limit

 function onOpen() {

  const ui = FormApp.getUi();
ui.createMenu('自動關閉設定')
.addItem('設定人數上限', 'showLimitDialog')
.addToUi();

}

function showLimitDialog() {
const ui = FormApp.getUi();
const limitResponse = ui.prompt(
'人數限制',
'請輸入人數上限:',
ui.ButtonSet.OK_CANCEL

);

if (limitResponse.getSelectedButton() == ui.Button.OK) {
const limit = parseInt(limitResponse.getResponseText().trim(), 10);
if (!isNaN(limit)) {
setLimitTrigger(limit);
ui.alert(`已設置人數上限為 ${limit},表單將在達到上限時自動關閉。`);
} else {
ui.alert('輸入無效。請輸入有效的數字。');
}

}
}

function setLimitTrigger(limit) {
const form = FormApp.getActiveForm();

// 刪除現有的觸發器,以避免重複
ScriptApp.getProjectTriggers().forEach(trigger => {
if (trigger.getHandlerFunction() === 'closeFormWhenLimitReached') {
ScriptApp.deleteTrigger(trigger);
}

});

// 設置「回應提交」觸發器以立即檢查條件
ScriptApp.newTrigger('closeFormWhenLimitReached')
.forForm(form)
.onFormSubmit()
.create();


// 將設定存入 Script Properties
PropertiesService.getScriptProperties().setProperties({
formId: form.getId(),
responseLimit: limit.toString()

});

// 立即檢查一次,確認條件是否已經達成
closeFormWhenLimitReached();
}

function closeFormWhenLimitReached() {
const formId = PropertiesService.getScriptProperties().getProperty('formId');
const responseLimit = parseInt(PropertiesService.getScriptProperties().getProperty('responseLimit'), 10);

if (!formId) {
Logger.log('未找到表單 ID,無法檢查條件');
return;

}

const form = FormApp.openById(formId);
const responses = form.getResponses().length;

// 檢查回應數是否達到上限
if (responses >= responseLimit) {
form.setAcceptingResponses(false);
Logger.log(`表單已達到回應上限 ${responseLimit},已自動關閉`);

} else {
Logger.log(`目前回應數:${responses},尚未達到上限 ${responseLimit}`);

}
}

沒有留言:

張貼留言

mbit

micro:bit 是由英國廣播公司 BBC 和微軟共同開發推出的一款微電腦開發板,目的是為了要讓全世界的學生或是對程式設計有興趣的大人,知道軟體和硬體如何整合在一起,對於初學者來說是非常好入門的一款開發板。 https://microbit.org/projects/make-...