Initially I had everything working with Chosen plugin when the options were directly passed from python to the html template.
I then tried to make the options filled dynamically depending on one of the buttons clicked, the options were not rendered so nothing showed up (but if I inspect the Elements, each optgroup was filled correctly with options).
And if I remove $(".chosen-select").chosen() , then the options are rendered.
Here's my code:
<!-- language: html -->
<div class="container" style="margin:auto; padding-top: 2%; text-align: center;">
<b>Choose the Program:</b>
<ul id="programs" class="no-bullets" data-tag="programList">
<li onclick="selectProgram(this)">Type1</li>
<li onclick="selectProgram(this)">Type2</li>
<li onclick="selectProgram(this)">Type3</li>
</ul>
<b>Choose the Documents:</b>
<select id="documentOptions" name="documents" data-placeholder="Your Documents" class="chosen-select" multiple>
<optgroup label="Group1" id="Group1"></optgroup>
<optgroup label="Group2" id="Group2"></optgroup>
<optgroup label="Group3" id="Group3"></optgroup>
</select>
</div>
<!-- language: lang-js -->
<script>
$(".chosen-select").chosen()
function selectProgram(el){
Array.prototype.slice.call(document.querySelectorAll('ul[data-tag="programList"] li')).forEach(function(element){
element.classList.remove('selected');
});
el.classList.add('selected');
programSelected = el.innerText;
//console.log(programSelected);
fetch(`/api/data/get_program/${programSelected}`)
.then(function(response){
return response.json();
}).then(function(documentList){
documentListJSON = {"documents":documentList};
//console.log(documentListJSON);
$.ajax({
type: 'POST',
url: '/api/data/programDocuments',
contentType: 'application/json',
data: JSON.stringify(documentListJSON),
success: function( allDocuments ){
console.log(allDocuments);
const Type1_Options = document.getElementById("Group1");
const Type2_Options = document.getElementById("Group2");
const Type3_Options = document.getElementById("Group3");
Type1_Options.innerHTML = "";
Type2_Options.innerHTML = "";
Type3_Options.innerHTML = "";
let docs_type1 = allDocuments['type1'];
let docs_type2 = allDocuments['type2'];
let docs_type3 = allDocuments['type3'];
// create list of options
var options = "";
for(var i = 0; i<docs_type1.length;i++){
options += "<option value='" + docs_type1[i] +"'>" + docs_type1[i] + "</option>";
}
Type1_Options.innerHTML += options;
$(Type1_Options).appendTo('#Group1');
var options = "";
for(var i = 0; i<docs_type2.length;i++){
options += "<option value='" + docs_type2[i] +"'>" + docs_type2[i] + "</option>";
}
Type2_Options.innerHTML += options;
$(Type2_Options).appendTo('#Group2');
var options = "";
for(var i = 0; i<docs_type3.length;i++){
options += "<option value='" + docs_type3[i] +"'>" + docs_type3[i] + "</option>";
}
Type3_Options.innerHTML += options;
$(Type3_Options).appendTo('#Group3');
}
})
})
}
</script>
I'm quite new to JavaScript and Jquery..Could someone please help explain why this happens?
Any help is very much appreciated. Thank you!
I am trying to speed up my script, right now I currently have it set up so that on a button click a custom dialog (HTML) appears asking some questions. On submit, it calls out a gs function to pull the info back as variables. Depending on the first answer I have a series of If statments that trigger. Each of them pull up a different template, make a copy, populate some cells, emails it to you, and then dumps the data into a tracker. Each of them are different so the script is rather long - is there a way to have each if statment its own function? Would this even help the speed? I am new to scripting so any feedback is appreciated. Below is the Code and HTML
function onOpen() //adds option to top row in case buttons are not working.
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Create Doc.')
.addItem('Create Tracked Document', 'addItem')
.addToUi();
}
function addItem()//starts the initiation process
{
var html = HtmlService.createTemplateFromFile('form')
.evaluate()
.setWidth(300)
.setHeight(550);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Create New Document');
}
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
var Newform2= templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform2);
var dropSheet = qs.getSheetByName("blank");
var URL3 = Newform2.getUrl();
dropSheet.getRange("i8").setValue(title);
dropSheet.getRange("bc5").setValue(now);
dropSheet.getRange("b5").setValue(platform);
dropSheet.getRange("p5").setValue(area);
dropSheet.getRange("x5").setValue(rota);
dropSheet.getRange("al5").setValue(works);
dropSheet.getRange("at6").setValue(name);
NewOPLPOA.setSharing(DriveApp.Access.DOMAIN,DriveApp.Permission.COMMENT);
NewOPLPOA.setOwner("ME");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
}
else if (form_data.Document_Type == "Text1"){
var dumpfolder = DriveApp.getFolderById("abcd")
var templateSheet = DriveApp.getFileById("bgtrd");
var Newform1 = templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform1);
var dropSheet = qs.getSheetByName("DOC1");
var URL4 = Newform1.getUrl();
dropSheet.getRange("aa3").setValue(platform);
dropSheet.getRange("ah3").setValue(area);
dropSheet.getRange("ao3").setValue(works);
NewSEWO.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.COMMENT);
NewSEWO.setOwner("Me");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL4]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL4);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL4, ui.ButtonSet.OK);
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
}
--HTML--
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myform">
<div class="form-group">
<label for="Document_Type">Document Type</label>
<select class="form-control" id="Document_Type" name = "Document_Type" required="required">
<?
var SS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Set Up");
var Avals = SS.getRange("A2:A").getValues();
var numberOfValues = Avals.filter(String).length;
var RangeVals = SS.getRange(2,1,numberOfValues).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeVals.length; ++i) { ?>
<option><?!= RangeVals[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for ="Name">Your Name</label>
<select class="form-control" name='Name' id="Name" required="required">
<?
var AvalN = SS.getRange("E2:E").getValues();
var numberOfValuesN = AvalN.filter(String).length;
var RangeValsN = SS.getRange(2,5,numberOfValuesN).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsN.length; ++i) { ?>
<option><?!= RangeValsN[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Platform">Platform</label>
<select class="form-control" id="Platform" name = "Platform" required="required">
<?
var AvalP = SS.getRange("C2:C").getValues();
var numberOfValuesP = AvalP.filter(String).length;
var RangeValsP = SS.getRange(2,3,numberOfValuesP).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsP.length; ++i) { ?>
<option><?!= RangeValsP[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Area">Area</label>
<select class="form-control" id="Area" name = "Area" required="required">
<?
var AvalA = SS.getRange("D2:D").getValues();
var numberOfValuesA = AvalA.filter(String).length;
var RangeValsA = SS.getRange(2,4,numberOfValuesA).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsA.length; ++i) { ?>
<option><?!= RangeValsA[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="Rotation">Rotation</label>
<select class="form-control" name='Rotation' id="Rotation">
<?
var AvalR = SS.getRange("F2:F").getValues();
var numberOfValuesR = AvalR.filter(String).length;
var RangeValsR = SS.getRange(2,6,numberOfValuesR).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsR.length; ++i) { ?>
<option><?!= RangeValsR[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="WorkSt">Work Station</label>
<input type='text' name='WorkSt' id="WorkSt" />
</div>
<div class="block form-group">
<label for="Title">Title</label>
<input type='text' name='Title' id="Title" required="required"/>
</div>
<div class="block">
<button type="submit" class="action">Submit</button>
</div>
</form>
<script>
document.querySelector("#myform").addEventListener("submit",
function(e)
{
e.preventDefault(); //stop form from submitting
google.script.run.addNewItem(this);
google.script.host.close();//close this dialogbox
}
);
</script>
</body>
</html>
is there a way to have each if statement its own function?
For visibility purposes, you certainly can modify your code as
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
function1();
}
else if (form_data.Document_Type == "Text1"){
function2();
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
function function1(){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
...
}
function function2(){
var dumpfolder = DriveApp.getFolderById("abcd")
...
}
Would this even help the speed?
Not really. To help up speed, you should rather try to implement Best Practices.
In particular: Reduce repeated calls to external services, including SpreadsheetApp.
For example, try to position the cells to which you want to assign values into an adjacent range, so you can use the method setValues() instead of multiple setValue() and thus make your code more efficient.
Sample:
var range = dropSheet.getRange("I8:N8");
var values = [];
values[0] = [];
values[0].push(title, now, platform, area, rota, works, name);
range.setValues(values);
Also, try to avoid repeating the same request for each if condition and rather make a single request after exiting the if statement, e.g. for:
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
I hope this helps!
I tried to select the inline styles in p tag and div tag only. But no need to select td, inline styles
regex style=[\"\w\d\.\:\-\'\s\#\;]+
Input:
<p class="Test"><span style="font-family:Verdana">?</span><span style="font:7.0pt 'Times New Roman'"> </span><span>AAA</span></p>
<table cellspacing="0" cellpadding="0" style="border-collapse:collapse; margin-left:0pt">
<tr>
<td style="border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt">
<p class="Tabelle" style="margin-top:3pt; margin-bottom:3pt"><span style="font-family:Tahoma; font-size:9pt">Detail</span></p>
</td>
output:
style="margin-top:3pt; margin-bottom:3pt in p tag
Note:
I need to select only p tag, div tag tags inline styles.
You can try this:
Find by:
(<(?:p|div)[^<]*)(style="[^"]*")([^>]*>)
replace by:
$1$3
C# Code Sample:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string pattern = #"(<(?:p|div)[^<]*)(style=""[^""]*"")([^>]*>)";
string substitution = #"$1$3";
string input = #"<p class=""Test""><span style=""font-family:Verdana"">?</span><span style=""font:7.0pt 'Times New Roman'""> </span><span>AAA</span></p>
<table cellspacing=""0"" cellpadding=""0"" style=""border-collapse:collapse; margin-left:0pt"">
<tr>
<td style=""border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt"">
<p class=""Tabelle"" style=""margin-top:3pt; margin-bottom:3pt""><span style=""font-family:Tahoma; font-size:9pt"">Detail</span></p>
</td>
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
System.Console.WriteLine(result);
}
}
Explanation
You get yoru data in group 1
I'm trying to modify a template in TYPO3 and I can modify some parts of the page, but not some other parts that are 1 level deeper. For example :
HTML
<body>
...
<div class="wrapper">
...
<div id="content-right">
<div id="colRight">
<div id="metaNav"></div>
</div>
</div>
...
</div>
...
</body>
Typoscript
page.10.subparts {
colRight = HMENU
colRight.wrap = <ul>|</ul>
colRight.special.value = 6, 7, 8, 9
colRight.1 = TMENU
colRight.1 {
noBlur = 1
NO = 1
NO {
allWrap = <li>|</li>
}
}
}
But if I change colRight with metaNav (because this is where we want the links so we can place other contents in colRight), nothing happens; no content is displayed. Why?
While you have it mapped to #colRight and have problem with mapping it to its child div you can just add a HTML markup to element's wrap:
page.10.subparts {
colRight = HMENU
colRight.wrap = <div id="metaNav"><ul>|</ul></div>
// etc...
}
With rule #1: In TS every way is the best solution to get immediate results :)
edit
if you need to render many different elements under one HTML tag, you can also use COA element to span them:
page.10.subparts {
colRight = COA
colRight {
10 = HMENU
10 {
wrap = <div id="metaNav"><ul>|</ul></div>
// etc...
}
20 = TEXT
20 {
value = my text in #colRight right after #metaNav
wrap = <div class="containerAfterMetsNav">|</div>
}
}
}
If someone knows please help me to build a regular expression that will valid
- no special characters allow in the file name
- only MS Word file can be uploaded (.docx,.doc, excel, ppt, etc)
- file name can not be more than 80 characters
Thanks
What language? Try this:
/^[A-Za-Z][A-Za-z0-9_ ]\.(docx|doc|xls|ppt|etc)$/
and then check length separately. You'll need to extend/edit the suffix list (etc is obviously not a legit suffix. :)
[a-z0-9A-Z-\s*]{1,80}\.(docx|doc|excel|ppt)
Add whatever file extensions you need seperated by |
All credits go to finalwesites.com, I've tweaked their demo file to fit your needs.
Live demo (without the tweak) at http://www.finalwebsites.com/demos/php_file_upload.php
<?php
require dirname(__FILE__).'/upload_class.php'; // Download it # http://pastebin.com/zAsn8V6R
$folder = dirname(__FILE__)."/upload/"; // "upload" is the folder for the uploaded files (you have to create this folder)
function select_files($dir) {
// removed in ver 1.01 the globals
$teller = 0;
if ($handle = opendir($dir)) {
$mydir = "<p>These are the files in the directory:</p>\n";
$mydir .= "<form name=\"form1\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">\n";
$mydir .= " <select name=\"file_in_folder\">\n";
$mydir .= " <option value=\"\" selected>...\n";
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
sort($files);
foreach ($files as $val) {
if (is_file($dir.$val)) { // show only real files (ver. 1.01)
$mydir .= " <option value=\"".$val."\">";
$mydir .= (strlen($val) > 30) ? substr($val, 0, 30)."...\n" : $val."\n";
$teller++;
}
}
$mydir .= " </select>";
$mydir .= "<input type=\"submit\" name=\"download\" value=\"Download\">";
$mydir .= "</form>\n";
}
if ($teller == 0) {
echo "No files!";
} else {
echo $mydir;
}
}
if (isset($_POST['download'])) {
$fullPath = $folder.$_POST['file_in_folder'];
if ($fd = fopen ($fullPath, "rb")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "docx":
header("Content-type: application/docx");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "doc":
header("Content-type: application/doc");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "xls":
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "ppt":
header("Content-type: application/ppt");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "txt":
header("Content-type: application/txt");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
case "odt":
header("Content-type: application/odt");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
}
function del_file($file) {
$delete = #unlink($file);
clearstatcache();
if (#file_exists($file)) {
$filesys = eregi_replace("/","\\",$file);
$delete = #system("del $filesys");
clearstatcache();
if (#file_exists($file)) {
$delete = #chmod ($file, 0775);
$delete = #unlink($file);
$delete = #system("del $filesys");
}
}
}
function get_oldest_file($directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if (is_file($directory.$file)) { // add only files to the array (ver. 1.01)
$files[] = $file;
}
}
if (count($files) <= 12) {
return;
} else {
foreach ($files as $val) {
if (is_file($directory.$val)) {
$file_date[$val] = filemtime($directory.$val);
}
}
}
}
closedir($handle);
asort($file_date, SORT_NUMERIC);
reset($file_date);
$oldest = key($file_date);
return $oldest;
}
$max_size = 1024*2000; // the max. size for uploading = 2000 KB, change this to fit your needs
$my_upload = new file_upload;
$my_upload->upload_dir = $folder;
$my_upload->extensions = array(".docx", ".ppt", ".doc", ".pdf", ".xls", ".odt", ".txt"); // specify the allowed extensions here
if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
$my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n";
$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n";
if ($my_upload->upload()) {
$latest = get_oldest_file($folder);
del_file($folder.$latest);
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Demo: File upload/download and open directory</title>
<style type="text/css">
<!--
body {
font-family: Arial, Helvetica, sans-serif;
text-align:center;
}
p {
font-size: 14px;
line-height: 20px;
}
label {
font: 14px/20px Arial, Helvetica, sans-serif;
margin-top: 5px 0 0;
float:left;
display:block;
width:120px;
}
#main {
width:350px;
margin:0 auto;
padding:10px;
text-align:left;
border: 1px solid #000000;
}
input {
margin-left:5px;
}
-->
</style>
</head>
<body>
<div id="main">
<h2 style="text-align:center;margin-top:10px;">Demo page:</h2>
<p align="center">(File upload/download and open directory)</p>
<p>Max. filesize: <b><?php echo $max_size/1024; ?> KB</b><br>
<?php
$ext = "Allowed extensions are: <b>";
foreach ($my_upload->extensions as $val) {
$ext .= ltrim($val, ".").", ";
}
echo rtrim($ext, ", ")."</b>";
?>
</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>">
<center><input type="file" name="upload" id="upload" size="25"></center>
<label for="replace">Replace?</label>
<input type="checkbox" name="replace" id="replace" value="y"><br clear="all">
<label for="check">Validate filename ?</label>
<input name="check" type="checkbox" id="check" value="y" checked>
<br clear="all">
<center><input type="submit" name="Submit" id="Submit" value="Submit"></center>
</form>
<p style="margin-top:20px;color:#FF0000;"><?php echo $my_upload->show_error_string(); ?></p>
<?php echo select_files($folder); ?>
</div>
</body>
</html>