Get the selected value in google app script - javascript

How to pass a select box value.
I have a spreadsheet where i want to filter based on a select box value.
I made a way to call the app function on form submit. But I am not able to pass one more parameter at the other side.
I want to filter based on the select box value and thereby retrieve the result from the spreadsheet on to the web app. This is my selectbox in html.
Select DATA
<select name ="productId" id="gettheVAL">
<option>DATA1 </option>
<option>DATA2 </option>
<option>DATA3 </option>
</select>
Can anyone guide me on this? I have called the function via this
form.on('submit', function(event){
event.preventDefault();
runner.withSuccessHandler(function(array){
for (var i = 0; i < array.length; i++) {
var item = '<tr><td>' + array[i] +'</td></tr>';
table.append(item);
}
}).retrieveValuesFromForm(this);
Update
Adding the function - retrieveValuesFromForm below:
function retrieveValuesFromForm(req) {
//var selectedvalue=$('input[name="gettheSelectValue"]:checked').val();// tried like this but $ is undefined here
var sheetActive = SpreadsheetApp.openById("SHEETID");
var sheet = sheetActive.getSheetByName("SHEETNAME");
var range = sheet.getRange('A:U');
var rawData = range.getValues();
var data = [];
for (var i = 0; i < rawData.length; i++) {
if ((rawData[i][2] == selectedvalue)) // Check to see if column 3 says selectedvalue if not skip it
{
//processing
}
}
return data;
}

Based on the assumption that you have a field in your form such as
<select name ="productId" id="gettheVAL">
In your form, You could call your Google App Script function with the following parameter
runner.withSuccessHandler(function(array){
...
}).retrieveValuesFromForm($("#gettheVAL").val());
You would then change the signature for retriveValuesFromForm
function retrieveValuesFromForm(selectVal) {
...
}

Here's how I pass a selected option and a few other things.
function sendText()
{
var culr=$('input[name="priority"]:checked').val();
var type=$('#sel1').val();
var txt=$('#txt1').val();
var obj={'type':type,'text':txt,'color':culr};
$('#txt1').css('background-color','#ffff00');
google.script.run
.withSuccessHandler(clearText)
.dispText(obj);
}
I'm guessing that you need to add this line into your head tag area.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Related

Google Script and Google Sheets - Drop down to select cell and add value from input from sidebar

I have been cobbling together script from other sources and feel like I am close but can't make that final leap on my own. Just to give you some background
I am putting together a document in Google Sheets where I can have a student input specific values from a live football game, that will be used on OBS to be displayed as real time stats for our video broadcast. I made a very simple button based sheet for basketball and it worked fantastically. Picture of Google Basketball Sheet
Football is a different beast. My concept is to have a sidebar where I have a set of names preselected in a drop down menu along with a second drop down menu with a preselected drop down of stat types (rush, passing....) these two drop downs will find the cell associated with both with Name rows) and stat type (column) and a input field which adds value to selected cell.
I have not been able to figure out how to have a drop down menu associate with a specific cell, let alone two different drop downs. If the two drop downs isn't possible, I am happy with making a button to associate with specific plays then have a drop down of names along with an input field will work.
What I have so far - I have a drop down menu that pulls the names from Column A but when I select one, nothing happens. I also have a button that I can send a value to a specific cell, but it won't add to the original cell it just changes the cell to "Input value"1
function ftball() {
try {
var output = HtmlService.createHtmlOutputFromFile('HTML_Sidebar');
SpreadsheetApp.getUi().showSidebar(output);
}
catch(err) {
Logger.log(err);
}
}
function getNames() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Football");
return sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues(); // Retrieve values and send to Javascript
}
// Sets the value of A1 cell to value entered in the input field in the side bar!
function enterValue(number){
var ss = SpreadsheetApp.getActive()
var sheet = ss.getActiveSheet()
sheet.getRange("B11").setValue(number + 1)
}
and the HTML for the Sidebar
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="mySelect" onchange="selectChange(this)">
</select>
<script>
function selectChange(select) {
google.script.run.changeSheet(select.value);
}
function playerNames(names) {
var select = document.getElementById("mySelect");
for( var i=0; i<names.length; i++ ) {
var option = document.createElement("option");
option.text = names[i];
select.add(option);
}
}
(function () { google.script.run.withSuccessHandler(playerNames).getNames(); }());
</script>
<button onclick='f1()'>Select Athlete Name</button>
</br>
<!-- Create a input field to except a value form user, in this case there name -->
Enter Value:
<input type="number" id="number"><br>
<!-- Create a button to send the value to the spreadsheet -->
<button onclick='sendValue()'>Send Value</button>
<script>
function f1() {
google.script.run.getAddress();
}
function sendValue(){
//Get the value of the input field
var number = document.getElementById("number").value
//Log the value of input field in the web browser console (usually used for debugging)
console.log(number)
//Send the value of the text field as a arugment to the server side function.
google.script.run.enterValue(number)
}
</script>
</body>
</html>
I am able to create something from yours using my own sample data and not sure if this is what you want but I tried to adjust to anything I understood in your post. See output and code below.
Code.gs:
function ftball() {
try {
var output = HtmlService.createHtmlOutputFromFile('HTML_Sidebar');
SpreadsheetApp.getUi().showSidebar(output);
}
catch(err) {
Logger.log(err);
}
}
function getData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Football");
return [sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues().filter(String), // Retrieve names and
sheet.getRange(1, 2, sheet.getLastRow(), 1).getValues().filter(String)]; // Stat types then send to Javascript (remove blank cells)
}
function enterValue(number, name, stat){
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var namesLength = sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues().filter(String).length;
var statsLength = sheet.getRange(1, 2, sheet.getLastRow(), 1).getValues().filter(String).length;
// where your name headers for the table starts (C6)
var nameStartRow = 6;
var nameStartCol = 3;
// where your stat headers for the table (D5)
var statStartRow = 5;
var statStartCol = 4;
// get list of names
var names = sheet.getRange(nameStartRow, nameStartCol, namesLength, 1).getValues().flat();
var stats = sheet.getRange(statStartRow, statStartCol, 1, statsLength).getValues().flat();
// find the position by adjusting the index of name/stat to where the list starts
var namePosition = names.indexOf(name) + nameStartRow;
var statPosition = stats.indexOf(stat) + statStartCol;
// get previous value, assign 0 if blank.
var previousValue = sheet.getRange(namePosition, statPosition).getValue() || 0;
sheet.getRange(namePosition, statPosition).setValue(parseInt(previousValue) + parseInt(number));
}
HTML_Sidebar.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="mySelectNames"></select>
<select id="mySelectStats"></select><br>
Enter Value:
<input type="number" id="number"><br>
<button onclick='sendValue()'>Send Value</button>
<script>
function setOptions([names, stats]) {
// set both names and stats drop down
var select = document.getElementById("mySelectNames");
for( var i=0; i<names.length; i++ ) {
var option = document.createElement("option");
option.text = names[i];
select.add(option);
}
// set default value to first option
select.selectedIndex = 0;
var select2 = document.getElementById("mySelectStats");
for( var i=0; i<stats.length; i++ ) {
var option2 = document.createElement("option");
option2.text = stats[i];
select2.add(option2);
}
select2.selectedIndex = 0;
}
function sendValue(){
// send the values of name, stat and number then set as value
var number = document.getElementById("number").value;
var name = document.getElementById("mySelectNames").value;
var stat = document.getElementById("mySelectStats").value;
//Send the value of the text field as a arugment to the server side function.
google.script.run.enterValue(number, name, stat);
}
(function () { google.script.run.withSuccessHandler(setOptions).getData(); }());
</script>
</body>
</html>
Output:
Note:
I modified both your html and apps script. But I hope it is near what you are wanting to achieve.
The important bit here is how to find where to put the value given the name and stat. That's what I think is you can use and modify based on your data and wanted output.
The code needs A and B to be not populated, thus the table is a bit to the right. But it can be avoided if we exactly know the list of names and stats.

How to get the CheckBoxlist value using JavaScript

Using below javascript function can able to get the all the text of checkbox list. But can't able to get the value (It passing as "on").
var CHK = document.getElementById("<%=chkFun.ClientID%>");
var checkbox = CHK.getElementsByTagName("input");
var label = CHK.getElementsByTagName("label");
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < checkbox.length; i++) {
var value = checkbox[i].value;
alert("Selected = " + label[i].innerHTML); //Get the text
}
The default value of a checkbox is "on" which is what you are getting. You are not setting the value of the checkbox properly.
If the value attribute was omitted, the default value for the checkbox is on , so the submitted data in that case would be [name]=on.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

Get Selected Row Value In Kendo Grid

I'm able to get the selected row in kendo grid, But I'm unable to get the specific selected row data in detail grid.
One thing that I expect is just get the Ticket_ID field string "5d484b061bf03".
I've tried to make my code just like this:
function onChange(arg) {
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
myWindow.data("kendoWindow").open();
undo.fadeOut();
console.log(selected.TICKET_ID);
}
But just getting "undefined".
Any well thought to advise will be appreciated.
Thanks
jQuery $.map returns an array constructed of return values, and you are returning strings.
See Telerik example in API reference for kendo.ui.Grid change to see more about getting the data items used to construct the selected grid rows. The data items will have a field corresponding to the ticket_id value. The name of the field is case-sensitive.
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
console.log (dataItem);
selectedDataItems.push(dataItem);
}
// selectedDataItems contains all selected data items
}
you can get and persist selected row on a specific page after edit or paging in change and databound events like this:
Grid_OnRowSelect = function (e) {
this.currentPageNum = grid.dataSource.page();
//Save index of selected row
this.selectedIndex = grid.select().index();
}
.Events(e => e.DataBound(
#<text>
function(e)
{
//جهت نمایش صحیح پیجینگ
var grid = $("#Grid").data("kendoGrid");
grid.pager.resize();
//در صورت تغییر صفحه، سطر را انتخاب نکند
if(this.currentPageNum == grid.dataSource.page())
{
//انتخاب مجدد سطر انتخاب شده قبل از ویرایش
var row = grid.table.find("tr:eq(" + this.selectedIndex + ")");
grid.select(row);
}
}
</text>)
)

Getting form element by value in Javascript

Hey guys I have a form which is stated below
<td><input type="text" id="NumberofRisks" name="Yeses" style="width: 25px" value ="<?php echo $row['Total-Score'];?> " </td>
The form has some data from a table as a value and I would like to take this value into my Javascript from to do a simple calculation. The function is listed below.
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = 0;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
I need to get that value into the function as the value where it says NumberofRisks. Is there a way I can do this?
Try this to set sum to the initial value of #NumberofRisks.
var prevCheckedCount = 0;
function sum()
{
var sumField = document.getElementById("NumberofRisks");
// start sum with the inital value in HTML from DB
var valueOnClick = Math.floor(sumField.value);
var thisCheckedCount = 0;
$("input[name^='yanswer']:checked").each(function(){
thisCheckedCount++;
});
if(thisCheckedCount <= prevCheckedCount) {
sumField.value = valueOnClick - prevCheckedCount + thisCheckedCount;
} else {
sumField.value =valueOnClick + thisCheckedCount;
}
prevCheckedCount = thisCheckedCount;
}
Here's this code working: http://jsfiddle.net/t5hG4/
In order to grab the value of the input box you can use the following javascript:
var sum = document.getElementById("NumberofRisks").value;
Is this what you're trying to achieve?
As a side note, in the example you provided you did not close the input box so that might be giving you some errors as well.
EDIT:
If you're looking for a pure Javascript way to do this see below:
var elements = document.getElementsByTagName('input');
var sum = document.getElementById("NumberofRisks").value;
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
sum++
}
}
See fiddle - http://jsfiddle.net/es26j/

Need a solution to this javascript coding problem

I have a SELECT in a FORM.
This select is populated using js.
I need to add a "Selected" attribute to one of these options.
I get which one, by checking a MySql database to see the name of the community which needs to have a "selected attribute" added to it.
<select name="community" id="community">
//OPTIONS HERE
</select>
The filler() function:
function filler(com){
//com is the options which needs to be selected, this variables value comes from the mysql database
var community = document.getElementById("community");
var area = document.getElementById("area").value;
// area is just another input on the page which value also is fetched from mysql db. Each area has x communities, so I have alot of IF:s.
if(area == 'Blekinge') {
community.length = 6;
community.options[0].value = "Välj Kommun";
community.options[0].text = "-- Välj Kommun --";
community.options[0].id = "Välj Kommun";
community.options[1].value = "Karlshamn";
community.options[1].text = "Karlshamn";
community.options[1].id = "Karlshamn";
community.options[2].value = "Karlskrona";
community.options[2].text = "Karlskrona";
community.options[2].id = "Karlskrona";
community.selected = 0;
}
}
As you can see, "com" variable is the option which needs to have the "selected" attribute added to it.
I have over 30 of these if-statements, and I have no clue how to create a function to add this "Selected" attribute to the matching option.
So I have "com" which for example could be "Karlskrona" in the example above. How should I add the selected to it?
I need a simple function for this which works in all major browsers...
Set the selectedIndex property of the SELECT to whichever index you need. Zero-based, of course.
Just do
community.value = com;
example at http://www.jsfiddle.net/jMapA/
for(var i = 0; i < community.options.length; i++) {
if(community.options[i].id == com)
community.selectedIndex = i;
}
function selectOptionValue(selectId, value)
{
select = document.getElementById(selectId);
if (select)
{
for (var i = 0; i < select.options.length)
{
if (select.options[i].value == value)
{
select.options[i].selected = 'selected';
return true;
}
}
}
return false;
}
Use my function like this:
selectOptionValue('community', 'Karlskrona');

Categories