Google Sheets HTML Sidebar Select Multiple Options with Comma-separated Output - html

I have a Google Sheets job tracker with an HTML sidebar interface for adding new jobs. The sidebar has some dropdowns that pull options from a different sheet.
For the "Upcharge" dropdown, I'd like to be able to select multiple options by holding Control and then have those selections separated by commas on output.
This is my HTML file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<b>Enter the details for your new job and click the <i><font color=#c5f27b>Save New Job</font></i> button.</b><br><br><br>
<table>
<tbody>
<tr>
<td><b>Upcharge:</b></td>
<td><select id="Upcharge">
<? for (let i in upchargeDPDWN) { ?>
<option value="<?=upchargeDPDWN[i]?>"><?=upchargeDPDWN[i]?></option>
<? } ?>
</select></td>
</tr>
<tr>
<td><b>Client:</b></td>
<td><select id="Client">
<? for (let i in clientDPDWN) { ?>
<option value="<?=clientDPDWN[i]?>"><?=clientDPDWN[i]?></option>
<? } ?>
</select></td>
</tr>
<tr>
<td><b>Description:</b> </td>
<td><input type="text" id="Description" size="22"><br></td>
</tr>
</tbody>
</table><br>
<!-- The user clicks this button to add the new job. -->
<center><input type="button" onclick='saveNew()' value="Save New Job"></center><br><br><br>
<script>
function saveNew(){
//Get the value of the input fields
var upcharge = document.getElementById("Upcharge").value
var client = document.getElementById("Client").value
var description = document.getElementById("Description").value
//Log input values in the web browser console
console.log(upcharge, client, description)
//Send values as arugments to the server side function
google.script.run.applyNew(upcharge, client, description)
}
</script>
</body>
</html>
This is my code to add the new job to the first empty row of the Job Log sheet:
function applyNew(upcharge, client, description) {
var ss = SpreadsheetApp.getActive()
var sheetLog = ss.getSheetByName("Job Log");
var sheetData = ss.getSheetByName("Data");
var rowCountData = sheetData.getMaxRows();
var columnToCheckData = sheetData.getRange("J:J").getValues();
var lastRowData = getLastRowSpecial(columnToCheckData);
if (lastRowData + 1 == rowCountData) {
sheetData.insertRowsAfter(lastRowData, 100);
}
// Get number of rows
var rowCount = sheetLog.getMaxRows();
//Select the column we will check for the first blank cell
var columnToCheck = sheetLog.getRange("B:B").getValues();
// Get the last row based on the data range of a single column.
var lastRow = getLastRowSpecial(columnToCheck);
// If the first empty row is the last row, insert a row before it
// (This is to ensure the data ranges for bar charts on the Dashboard sheet remain dynamic.)
if (lastRow + 1 == rowCount) {
sheetLog.insertRowAfter(lastRow);
}
var selectedRow = lastRow + 1;
//Apply upcharge to Column D = Column 4
sheetLog.getRange(selectedRow, 4).setValue(upcharge);
//Apply client to Column L = Column 12
sheetLog.getRange(selectedRow, 12).setValue(client);
//Apply description to Column N = Column 14
sheetLog.getRange(selectedRow, 14).setValue(description);
sheetLog.insertRowAfter(selectedRow);
};
Can someone please help me update this to allow for multiple options to be selected? All I can find via Google is scripts for selecting multiple items in data validation. Please let me know if any additional information is needed. Thanks in advance!

Here is a simple example of getting multiple options from a select element.
HTML_Test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="Upcharge" multiple size="4">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
<option value="option6">Option 6</option>
<option value="option7">Option 7</option>
<option value="option8">Option 8</option>
<option value="option9">Option 9</option>
<option value="option10">Option 10</option>
</select>
<br>
<input type="button" onclick='saveNew()' value="Save New Job">
<?!= include('JS_Test'); ?>
</body>
</html>
JS_Test.html
<script>
function saveNew() {
try {
let select = document.getElementById("Upcharge");
let options = select.options;
let selected = [];
for( let option of options ) {
if( option.selected ) selected.push(option.value);
}
alert(selected.toString());
}
catch(err) {
alert(err);
}
}
</script>
Screen shot
References
select multiple
select options

Related

Jquery returned 'undefined'(s) when try to get the ID of the 'select' tag through class

I'm trying to check if my select box is empty or not by using class. However, based on the code below, the alert returned not only the id but also another 2 'undefined'. Anyone who can tell me why is this happening?
<script>
$('.test-input').each(function () {
var el = [];
if ($(this).val() === "") {
var target = $(this).attr('id');
alert(target); *// return media_type | underfined | underfined*
el.push(target);
}
})
</script>
<div class="form-group col-sm-4">
<label class="">Type:</label>
<select class="form-control required-input test-input" id="media_type" placeholder="Choose a media">
<option value="">Select a state</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="lizard">Lizard</option>
<option value="snake">snake</option>
</select>
</div>
$('.test-input').each(function () will iterate through each element in your HTML that has the "test-input" class name, so when there you are cycling through those and getting an undefined from pulling its id via var target = $(this).attr('id');, what this means is that somewhere else in the file you must have two other classes named "test-input" without an ID.
I would console.log("Iteration"); in the loop and check your console to see how many times the loop is being run and go from there.

HTML how to save input depending on selected dropdown value

HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="" method="post">
<label>Select Fridge or Freezer</label>
<select name="FridgeFreezer">
<option value="Fridge 1">Fridge 1</option>
<option value="Fridge 2">Fridge 2</option>
<option value="Fridge 3">Fridge 3</option>
</select>
<label>Temperature °C</label>
<input type="number">
<label>Comments</label>
<textarea name="comments"></textarea>
<button type="button" name="button">Save</button>
</form>
</body>
</html>
Goal:
How can I select a value from the dropdown menu, for example, I have selected Fridge 1 from the menu, I then type some value in the Temperature °C and Comments box. Next select another value from drop down box as an example Fridge 2 and start a fresh input, but if I go back to Fridge 1 the data previously inputted to be visible.
What do I need to look into in terms of research? I am not sure where to look or what keywords to search.
I've put together a quick example of what I mentioned in the comments, using a simple array of objects the maintain each options previous state.
When the select is changed, we:
Check to see if we have an object for the previous id
If we do, update that object, otherwise, create a new one with the new values
Update the current id (We store this externally as it's lost by the time the change is executed)
Check for any saved data for the newly loaded id and load that if it exists
var savedValues = []
var currentId = document.getElementById("fridgeFreezer").value
function handleChange() {
// The new values for the fridge with id currentId:
var temp = document.getElementById("temperature").value
var comments = document.getElementById("comments").value
// Save these values for the previous id
// - First, check to see if we already have a record we can update
var save = savedValues.find(save => {
return save.id === currentId
})
// - If we do, update it, otherwise create a new record
if (save) {
save.temp = temp
save.comments = comments
} else {
savedValues.push({
id: currentId,
temp: temp,
comments: comments,
})
}
// Update the current id to the newly selected option
currentId = document.getElementById("fridgeFreezer").value
// Load any previously saved data for this new id
save = savedValues.find(save => {
return save.id === currentId
})
// If we find a previous value, load it, otherwise empty the inputs
if (save) {
document.getElementById("temperature").value = save.temp
document.getElementById("comments").value = save.comments
} else {
document.getElementById("temperature").value = ''
document.getElementById("comments").value = ''
}
}
// Attach the event listener to the document
document.getElementById("fridgeFreezer").addEventListener('change', handleChange, false)
label {
display: block
}
<form action="" method="post">
<label>Select Fridge or Freezer</label>
<select name="FridgeFreezer" id="fridgeFreezer">
<option value="Fridge 1">Fridge 1</option>
<option value="Fridge 2">Fridge 2</option>
<option value="Fridge 3">Fridge 3</option>
</select>
<label>Temperature °C</label>
<input type="number" id="temperature">
<label>Comments</label>
<textarea name="comments" id="comments"></textarea>
<button type="button" name="button">Save</button>
</form>
I highly recommend using Vue.js for this. State management is very easy in it. The way I would do this is:
var app = new Vue({
el: '#app',
data: function(){
return {
devices: [{id: 0, name: 'fridge1', tempCelcius: 39, price: 20},
{id: 1, name: 'fridge1', tempCelcius: 39, price: 30},
{id: 2, name: 'fridge1', tempCelcius: 39, price: 40}],
selected = ''
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app">
<select v-model="selected">
<option disabled value="">Please select one</option>
<option v-for="device in devices" v-bind:key="device.id">{{ device.name }}</option>
</select>
<span>{{ selected }}</span>
</div>
</body>
</html>
This is a start, it doesn't quite work yet but here is where you'll find how to implement

How to link option tags by name to a javascript if statement

I've been having some trouble coding one part of a webpage I am writing. The code looks something like this:
form name = dropDown
select
option name = "normalOne" /option
option name = "normalTwo" /option
/select
/form
Then:
if (document.dropDown.normalOne.selected == true) {
window.alert("drop down menu works");
}
Unfortunately, this does not work. What do I do?
Option elements don't have names (and the name attribute is not valid for them).
Deal with values instead.
document.querySelector("button").addEventListener("click", show);
function show(event) {
const select = document.querySelector("select");
const value = select.value;
console.log(value);
}
<select>
<option value="a"> One
<option value="b"> Two
<option value="c"> Three
</select>
<button>Log</button>
<!DOCTYPE html>
<html>
<body>
<select onChange="check(this.value)">
<option value="normalOne">normalOne</option>
<option value="normalTwo">normalTwo</option>
</select>
</body>
<script>
function check(value){
if (value === "normalOne") {
window.alert("drop down menu works");
}
}
</script>
</html>

Generate a url from a dropdown

Good morning,
I have the following issue.
I'm trying to setup a distance calculator from google maps.
Google is using its own api under that format:
https://maps.googleapis.com/maps/api/distancematrix/output?parameters
The output can be json or xml.
The idea is to use latitude and longitude to code the url:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=25.479838,-80.422374&destinations=25.55727,-80.33372
That's an example of how the api provides the output.
Now, I want to be able to generate the url from a list of latitudes and longitudes I have.
Both fields would be a dropdown with autocomplete (the datalist function seems useful for that)
And once I click on a button like Calculate distance, it will generate the url from the 2 inputs I chose, and run it, In order to provide me the output.
The output would be in json so we should also find a way to have it interpreted in html.
I really would appreciate some help on that.
Thank you
Since Distance Matrix API endpoint:
https://maps.googleapis.com/maps/api/distancematrix/output?parameters
doesn't support JSONP you might want to utilize Distance Matrix Service as part of the Google Maps Javascript API.
Example
function calc() {
var originVals = $('#origins').val();
var destVals = $('#destinations').val();
var modeVal = $('#modes').val();
calculateDistances(originVals, destVals, modeVal,printInfo);
}
function printInfo(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
console.log('An error occured: ' + status);
return;
}
var output = JSON.stringify(response, null, 2);
$("#output").text(output);
}
function calculateDistances(originVals, destVals, mode, callback) {
var origins = [];
originVals.forEach(function (val) {
var ll = val.split(',');
origins.push(new google.maps.LatLng(ll[0], ll[1]));
});
var destinations = [];
destVals.forEach(function (val) {
var ll = val.split(',');
destinations.push(new google.maps.LatLng(ll[0], ll[1]));
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: origins,
destinations: destinations,
travelMode: mode.toUpperCase()
}, callback);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<body>
<table>
<tr>
<td colspan="2">
<label for="modes">Travel Modes</label>
<select id="modes">
<option value="driving">Driving</option>
<option value="walking">Walking</option>
<option value="bicycling">Bicycling</option>
<option value="transit">Transit</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="origins">Origins</label>
</td>
<td>
<label for="destinations">Destinations</label>
</td>
</tr>
<tr>
<td>
<select id="origins" multiple="multiple">
<option value="49.256149, -123.074132">Vancouver+BC</option>
<option value="47.608136, -122.309813">Seattle</option>
</select>
</td>
<td>
<select id="destinations" multiple="multiple">
<option value="37.749624, -122.442407">San+Francisco</option>
<option value="48.430068, -123.365541">Victoria+BC</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input value="Calculate" type="button" onclick="calc();" />
</td>
</tr>
</table>
<br/>
<span>Result:</span>
<pre style="background-color: #c0c0c0" id="output"></pre>
</body>

Populating a combobox from a table in Webmatrix using CHTML

I'm a newby and am using Webmatrix (CHTML) to try and set up a form that allows the user to select an employee using a dropdownbox.
I think I understand how to make a list:
#{
var db = Database.Open("DatabaseName") ;
var selectCommand="SELECT ID,Employee FROM Employees";
var selectedData = db.Query(selectCommand);
var columns = new[]{"ID", "Employee"};
var grid = new WebGrid(source: selectedData, defaultSort: "Employee" , rowsPerPage:10,columnNames: columns);
}
#grid.GetHtml( )
and I think I know how to get a combobox:
<FORM NAME="myform">
<SELECT NAME="mylist">
<OPTION VALUE="01">Employee01
<OPTION VALUE="02">Employee02
<OPTION VALUE="03">Employee03
<OPTION VALUE="04">Employee04
<OPTION VALUE="05">Employee05 - and so on
</SELECT>
</FORM>
I just want to know how to get the table into the combobox. Would be very happy if someone could show how to do this.
This code creates a dropdown list from the content of your table:
#{
var db = Database.Open("DatabaseName");
var selectCommand = "SELECT ID, Employee FROM Employees";
var selectedData = db.Query(selectCommand);
}
<form name="myform" method="post">
<select name="mylist">
#foreach(var row in selectedData)
{
<option value="#row.ID">#row.Employee</option>
}
</select>
</form>