Get MultiSelect Option values using google app script - javascript

I have a list in google sheet to be selected as option in an html. The selection was set to multiple. How can I get the selected values be placed in a single cell in google sheet?
here is the link for the google sheet:
https://docs.google.com/spreadsheets/d/1lEfzjG1zzJVPMN8r-OpeZm6q9_IqSwk9DNCEY-q7ozY/edit?usp=sharing
here is my html code for multiple:
<div class="input-field col s4">
<select id="posApp" multiple="multiple">
<option value="" disabled>Choose your preferred app</option>
<?!= list2; ?>
</select>
<label>Select App</label>
</div> <!-- CLOSE TIME FIELD -->
</div> <!-- CLOSE ROW -->
for google script (to make a selection list from google sheet):
function doGet(e){
var ss = SpreadsheetApp.openByUrl(url);
var ws2 = ss.getSheetByName("Pos_App");
var list2 = ws2.getRange(1,1,ws2.getRange("A1").getDataRegion().getLastRow(),1).getValues();
var htmlListArray2 = list2.map(function(r){return '<option>' + r[0] + '</option>'; }).join('');
var tmp = HtmlService.createTemplateFromFile("page");
tmp.list2 = htmlListArray2;
return tmp.evaluate();
}
for javascript using initialization of Select from Materialize CSS and the code from #Cooper:
<script>
document.addEventListener('DOMContentLoaded', function() {
var timeSelect = document.querySelectorAll('select');
M.FormSelect.init(timeSelect);
document.getElementById("posApp").addEventListener("change",selectMulti);
function selectMulti(){
google.script.run.withSuccessHandler(updateSelect).getSelectOptions();
}
function updateSelect(vA){
var select = document.getElementById("posapp");
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
});
</script>
then additional function in google script also from #Cooper:
function getSelectOptions()
{
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Open_Pos");
var posRg = ws.getRange(1, 1, ws.getLastRow(), 1).getValues().join().split(",");
//return rg.getValue().split(',');
return posRg;
}
But unfortunately, it is still unsuccessful. Though the output in the HTML are all the selected data, when I click the submit button, only the 1st item in the selection were saved in the google sheet. I also don't know how to use .getSelectedValues(); from MaterializeCSS. Thank you in advance your your help.

Try this:
html:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select id="posApp" multiple="multiple"> <option value="" disabled>Choose your Position</option>
code.gs
function getSelectOptions()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Options');
var rg=sh.getRange('A1');
return rg.getValue().split(',');
}
javascript
function updateSelect(vA){
var select = document.getElementById("posapp");
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
$(function() {
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});

Related

How Add the Link in the Dropdown options?

Hi I'm working on script that I got in this forum.
Options are mentioned in the column A and Links are added in Column B, in the dropdown If I click the option 1 I want to open the respective link which is in Column B in another tab.
Code.gs
function doGet(e) {
return HtmlService.createTemplateFromFile("Index.html")
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSelectOptions()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Options');
var rg=sh.getDataRange();
var vA=rg.getValues();
var options=[];
for(var i=0;i<vA.length;i++)
{
options.push(vA[i][0]);
}
return vA;
}
function showSidebar()
{
var userInterface=HtmlService.createHtmlOutputFromFile('Index');
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'The Drop Down with No Options now has options.');
}
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(vA)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
console.log("My code");
</script>
</head>
<body>
<select id="sel1" style="width:125px;height:35px;margin:10px 0 10px 0;">
</select>
</body>
</html>
I couldn't figure it out how to embed the link into option. should another function defined for individual column or can it be done in single function?
Note: I'm not a coder.
You can use the onChange event to open the link when a user chooses an option
For this:
Use the syntax new Option(text, value). To pass the option and the link as the text and the value, you need to access the respective nested array elements:
select.options[i] = new Option(vA[i][0],vA[i][1]);
Use the method window.open() to open the link
Build an event handler function that accesses the selected value onChange with document.getElementById("sel1").value
Sample:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(vA)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i][0],vA[i][1]);
}
}
console.log("My code");
function myFunction(){
var value = document.getElementById("sel1").value;
window.open(value, '_blank');
}
</script>
</head>
<body>
<select id="sel1" style="width:125px;height:35px;margin:10px 0 10px 0;" onchange="myFunction()">
</select>
</body>
</html>

Google Sheets App Script Html onload not working

I'm using google sheets and I'm creating a document that will pull through employees that are out of the office. I have a menu option to remove employee data, and it opens the sidebar where I have an HTML form (Image of my project). I'm trying to have it generate a dropdown list of current employees on the list.
I've developed the code to pull through the data I need:
function removeAnyone() {
var html = HtmlService.createHtmlOutputFromFile('RemoveAnyone');
SpreadsheetApp.getUi()
.showSidebar(html);
}
function getList() {
var headerRows = 1;
var sheet = SpreadsheetApp.getActive().getSheetByName("Data");
var range = sheet.getRange(headerRows + 1, 1, sheet.getMaxRows() - headerRows, 1);
var arrayValues = range.getValues();
return arrayValues;
}
Now we move over to my html, where I am simply trying to load the dropdown list using a for loop in the header:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function addOption_list() {
document.getElementById("output").innerHTML = "test";
var options = google.script.run.getList();
for (var i = 0; i < options.length; ++i;) {
var optn = document.createElement("OPTION");
optn.text = options[i];
optn.value = options[i];
document.myForm.selectEmployee.options.add(optn);
}
}
</script>
</head>
<body onload="addOption_list()">
<form id="myForm" onsubmit="submitForm(this)">
<select id="selectEmployee">
<option>Choose an employee</option>
</select>
</form>
<div id="output"></div>
</body>
</html>
I threw a div in the body and have the function changing the value to "test" at the start, this was just to check and see if the function was even being called, which it doesn't seem like it is.
I also tried using window.onload (as shown below), but that didn't get me anywhere either.:
window.onload = function {
document.getElementById("output").innerHTML = "test";
var options = google.script.run.getList();
for (var i = 0; i < options.length; ++i;) {
var optn = document.createElement("OPTION");
optn.text = options[i];
optn.value = options[i];
document.myForm.selectEmployee.options.add(optn);
}
}
Any guidance you can give me would be really appreciated!
google.script.run doesn't return values. When you want to return values from GAS, please use withSuccessHandler. And the data retrieved by getValues() is 2 dimensional array. So how about this modification?
Modified script :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
window.onload = function() {
google.script.run.withSuccessHandler(addOption_list).getList();
}
function addOption_list(options) {
document.getElementById("output").innerHTML = "test";
var select = document.getElementById('selectEmployee');
for ( var i in options) {
var optn = document.createElement('option');
optn.value = options[i][0];
optn.text = options[i][0];
select.appendChild(optn);
}
}
</script>
</head>
<body>
<form id="myForm" onsubmit="submitForm(this)">
<select id="selectEmployee">
<option>Choose an employee</option>
</select>
</form>
<div id="output"></div>
</body>
</html>
Reference :
google.script.run
getValues()
If I misunderstand your question, I'm sorry.

change list options using google apps script

I want to load a list of items into a dropdown select box using a combination of html and javascript (google apps script).
I have been able to get all of the javascript functions to call and return values as expected, but when my code tries to add options to the select object, it seems to fail.
Here is my current HTML ('index'):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// The code in these functions run when the page is loaded.
google.script.run.withSuccessHandler(addItems).getFolderList();
//This function uses an array of folder names to create options for the select list
function addItems(folders){
alert('addItems was called!');
var htmlSelect = document.getElementById('folder');
for(var z = 0; z < folders.length; z++){
var selectBoxOption = document.createElement('OPTION');
selectBoxOption.value = folders[z];
selectBoxOption.text = folders[z];
htmlSelect.add(selectBoxOption); 
}
}
//this function lets the user know if the upload failed or not
function successMess(returnText) {
var div = document.getElementById('output');
div.innerHTML = '<p>'+returnText+'</p>';
}
</script>
</head>
<body>
<form id="myForm">
<p>Please choose a folder to receive the upload</p>
<select name="folder" id="folder">
<option value="Test Value">Test Value</option>
</select>
<br>
<input name="myFile" type="file" id="myFile"/>
<br>
<input type="button" value="Submit"
onclick="google.script.run.withSuccessHandler(successMess).processForm(this.parentNode)" />
</form>
<div id="output"></div>
</body>
</html>
Here is the accompanying JavaScript (.gs):
function doGet(){
return HtmlService.createHtmlOutputFromFile('index');
}
function processForm(formObject) {
var formBlob = formObject.myFile;
var folderName = formObject.folder;
var returnText = 'Please choose a valid file to upload';
if(formBlob.length > 0){
returnText = 'Your document was uploaded successfully!';
try{
var folder = DriveApp.getFoldersByName(folderName).next();
var driveFile = folder.createFile(formBlob);
}catch(e){
returnText = 'There was an error processing your document';
}
}
return returnText;
}
function getFolderList(){
Logger.log('getFolderList was called');
var ParentFolder = DriveApp.getFoldersByName('Test Folder').next();
var shopFolders = ParentFolder.getFolders();
var folderList = [];
while(shopFolders.hasNext()){
folderList.push(shopFolders.next().getName());
}
folderList.sort();
return folderList;
}
Everything is working beautifully...except the folder list population. I have manually populated the select options just to make sure the processForm function is working correctly. I have even tested (using another alert) to make sure that the folder name array from "getFolderList()" is being passed faithfully (and it is). It doesn't seem to have any problems getting the select item called "folder" or creating a new "option" item. It seems to fail when "addItems" tries to add the option to the list. Can anyone tell me what I'm doing wrong, and/or how to fix it?
Thanks!
Here is a solution to your problem:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="myForm">
<p>Please choose a folder to receive the upload</p>
<select name="folder" id="fldrList">
<option value="Test Value">Test Value</option>
</select>
<br>
<input name="myFile" type="file" id="myFile"/>
<br>
<input type="button" value="Submit"
onclick="google.script.run.withSuccessHandler(successMess).processForm(this.parentNode)" />
</form>
<div id="output"></div>
</body>
<script type="text/javascript">
// The code in these functions run when the page is loaded.
google.script.run.withSuccessHandler(addItems).getFolderList();
//This function uses an array of folder names to create options for the select list
function addItems(folders){
console.log('addItems was called!' + folders);
var htmlSelect = document.getElementById('fldrList');
console.log('htmlSelect: ' + htmlSelect);
var optionHTML = '';
for(var z = 0; z < folders.length; z++){
console.log('z: ' + z);
console.log('folders[z]: ' + folders[z]);
optionHTML = optionHTML + "<option value='" + folders[z] + "'>" + folders[z] + "</option>";
};
htmlSelect.innerHTML = optionHTML;
}
//this function lets the user know if the upload failed or not
function successMess(returnText) {
var div = document.getElementById('output');
div.innerHTML = '<p>'+returnText+'</p>';
}
</script>
</html>
Change the id name of your select element from folder to fldrList.
Unfortunately, the add method is not working. You can create the HTML in the form of a string and inject it.
Notice that the FOR LOOP creates an HTML string, then when the FOR LOOP is done, the HTML is injected into the SELECT element. It works. For some reason, Apps Script doesn't seem to be allowing the .add method. Don't know why.

Issue trying to get website to work - possible issue with my html code?

SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...
But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.
Here is my fiddle:
jsfiddle
^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...
And here is the actual site:
http://www.abveaspirations.com/index.html
And here's my HTML code uploaded to the server via FTP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- ##controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- ##controlbox -->
</div> <!-- 11main -->
</body>
And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!
You forgot to load jQuery. Make sure that you use <script src="../path-to-jquery/jquery.js"></script> before you load your script.js script.
Also, I noticed that you're loading your scripts in the head tag. This is bad practice, load them right before </body>.
I believe your site is missing jQuery. Add this to the top of your code to hotlink to google's jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Drop down menu showing improper images based on selection

I have a drop down box that will change an image if a new selection is made. Which i have got to work using the following code
<HTML>
<HEAD>
<TITLE>JS1</TITLE>
<script LANGUAGE="JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
<!--
image1 = new image(120,90)
image1.src = "desk1.gif"
image2 = new image(120,90)
image2.src = "desk2.gif"
image3 = new image(120,90)
image3.src = "desk3.gif"
image4 = new image(120,90)
image4.src = "desk4.gif"
function loadCatch(list)
{
var img = list.options[list.selectedIndex].value
document.thumbnail.src = eval(img + ".src")
}
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="desk1.gif" NAME="thumbnail" HEIGHT="90" WIDTH="120">
<FORM>
<SELECT NAME="catch" onChange="loadCatch(this)">
<OPTION VALUE="Image1">Bands
<OPTION VALUE="Image2">Clips
<OPTION VALUE="Image3">Lamp
<OPTION VALUE="Image4">Else
</SELECT>
</FORM>
</BODY>
</HTML>
The trouble is my form has 3-4 parts so when you click back to edit the form stays selected with the correct option selected but but the image shows the default image, I know this is because it is using an onChange event so I have investigated another way using the following code:
<script language="JavaScript" type="text/javascript">
<!--
var dropdownIndex = document.getElementById('colorsselect').selectedIndex;
var dropdownValue = document.getElementById('colorsselect')[dropdownIndex].value;
document.write(dropdownValue);
//-->
</script>
Which displays the correct image if I click to go back but it isn't live (onChange) so the user doenst get immediate result showing the new image.
I'm not sure how to combine the two pieces of code above, hope someone can help?
Call that same loadCatch function onload:
1) Add an id to the select box so you can reference it elsewhere:
<select id="catch" name="catch" onchange="loadCatch(this)">
2) Call loadCatch from on body load:
<body onload="loadCatch(document.getElementById('catch'))">
3) Adjust loadCatch to do nothing if a value hasn't been selected yet:
function loadCatch(list)
{
if (list.selectedValue != -1) {
var img = list.options[list.selectedIndex].value
document.thumbnail.src = eval(img + ".src")
}
}

Categories

Resources