How to Search Spreadsheet Using Google Visualization Query - javascript

I've got this simple webpage which uses google.visualization.Query to pull the values of three specific cells from this spreadsheet, and then sets the values of three corresponding input fields based on their unique id attributes.
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(work);
function work() {
var queryWORK = new google.visualization.Query('https://docs.google.com/spreadsheet/ccc?key=1HpHMfoEnPgESb2XPVCgb7XyGwRAvrq3EoQj4WHj4vhA&sheet=QUERY');
queryWORK.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in ID Validation Query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var datatable = response.getDataTable();
var name = datatable.getValue(1,0);
var job = datatable.getValue(1,1);
var hours = datatable.getValue(1,2);
document.getElementById('name_out').value = name;
document.getElementById('job_out').value = job;
document.getElementById('hours_out').value = hours;
}
As it is currently, I have to "hard code" the row and column indexes for each cell I want to pull data from. How can I can get this to search through and retrieve data from the spreadsheet? What, for example, if I had a simple input field where I could enter a name and the "job" and "hours" would be returned. Is this even possible?
Thanks.

you can use Query.setQuery to set a SQL-like statement,
which can be used to select certain columns and rows
the following will select the Job & Hours columns where Name = Bill
'select B, C where A = "Bill"'
you can also search for partial text, this will select both Bill and Kim
'select B, C where A like "%i%"'
following is a working snippet, the inputs are given the same names as the Columns
enter a full or partial name and click Search to see the results...
google.charts.load('current', {
callback: function () {
document.getElementById('Search').addEventListener('click', searchSheet, false);
searchSheet();
function searchSheet() {
searchText = document.getElementById('Name').value;
var queryWORK = new google.visualization.Query('https://docs.google.com/spreadsheet/ccc?key=1HpHMfoEnPgESb2XPVCgb7XyGwRAvrq3EoQj4WHj4vhA&sheet=QUERY');
if (searchText !== '') {
queryWORK.setQuery('select B, C where A like "%' + searchText + '%"');
}
queryWORK.send(function (response) {
if (response.isError()) {
console.log('Error in ID Validation Query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var datatable = response.getDataTable();
for (var i = 0; i < datatable.getNumberOfColumns(); i++) {
document.getElementById(datatable.getColumnLabel(i)).value =
(datatable.getNumberOfRows() > 0) ? datatable.getValue(0, i) : '';
}
var chart = new google.visualization.Table(document.getElementById('table_div'));
chart.draw(datatable);
});
}
},
packages:['table']
});
div {
padding: 6px 6px 6px 6px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div><label for="Name">Enter Name: </label><input id="Name" type="text" value="Bill" /></div>
<div><input id="Search" type="button" value="Search" /></div>
<div><label for="Name">Job: </label><input id="Job" type="text" /></div>
<div><label for="Name">Hours: </label><input id="Hours" type="text" /></div>
<div id="table_div"></div>

Related

Get user input in Webapp and display some rows in HTML

I have a sheet with ticket number, call date, customer mobile no, customer name
I want to take the user input (Ticket number) in a Webapp.
From that, I will find the customer mobile number in the table.
From the customer mobile number, I want to display all the matching rows (in the same table) to the user in HTML. I want to display all the calls made by the customer (he could have made many calls before)
I referred to
How to search and filter a Google Sheet based on two parameters in two different columns
and Tried
code.gs
function doGet() {
return HtmlService.createTemplateFromFile('index').evaluate();
}
//
function getValuesFromSS(search) {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1zObr0he1SYJkOXMMyFrOWk-0OtV6w/edit#gid=926906658")//service calls
var calsht=ss.getSheetByName('Calls');
//var lastRow = calsht.getLastRow();
var arange = calsht.getRange("A:D").getValues();
for (m= arange.length-1; m>0; m--){
if (arange[m][0]==search.name){//search.name
var cusmob=arange[m][3];
//Logger.log(m);
//Logger.log(cusmob);
}
}
var names = '';
var techs = '';
var eqips = '';
var urls = '';
var lastCol = calsht.getLastColumn();
for (m= arange.length-1; m>0; m--){
if (arange[m][3]==cusmob){
var values = calsht.getRange("A"+(m+1)+":AL"+(m+1)).getValues(); //get all values for the row
var name = values[0][4]; //column E
var tech = values[0][5]; //column F
var eqip = values[0][14]; //column O
var url = values[0][37]; // AL
//Logger.log(url);
names+=Utilities.formatString("<td>" + name + "</td>");
techs+=Utilities.formatString("<td>" + tech + "</td>");
eqips+=Utilities.formatString("<td>" + eqip + "</td>");
urls+=Utilities.formatString('<td>' + 'Inv' + '</td>');
}//if
}//for
return {
first: names,
second: techs,
third: eqips,
fourth: urls
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function setPageValues () {
var search = document.getElementsByName('searchtext')[0].value;
var obj = {};
if (!search) alert("Ticket No is required");
if (search) {
obj.name = search;
}
google.script.run.withSuccessHandler(disp).getValuesFromSS(obj);
}
function disp(values){
document.getElementById("results1").innerHTML = values.first;
document.getElementById("results2").innerHTML = values.second;
document.getElementById("results3").innerHTML = values.third;
document.getElementById("results4").innerHTML = values.fourth;
}
</script>
</head>
<style>
table {
border-collapse: collapse;
}
tr {
display: block;
float: left;
}
td {
border: 1px solid Black;
display: block;
}
</style>
<body>
<input type="text" name="searchtext">
<input type="button" value="Search" onclick="setPageValues();">
<br>
<div name="resultbox">
<table>
<tr id="results1">
</tr>
<tr id="results2">
</tr>
<tr id="results3">
</tr>
<tr id="results4">
</tr>
</table>
</div>
</body>
<script>
</script>
</html>
Now it seems to be working.
I changed from findall to for loop.
Take a look at google.script.run
you can display your results with the withSuccessHandler

how to get and render selected values related data from array in jquery?

I have no expertise in javascript but I want to render this data which is showing in my console.log below
How can I make forloop or something like that to render this data in my html input?
create.html
<div class="col-sm-2">
<div class="form-group">
<label>Expected Values</label>
<input type="text" class="form-control" value="{{vital.expected_values}}" readonly>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Price</label>
<input type="text" class="form-control" value="{{vital.price}}" readonly>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#id_vitals").change(function () {
var vitals = $(this).val();
$.ajax({
url: $('#personForm').data('url'),
data: { 'vital_id': vitals },
success: function (response) {
console.log(response[vitals['name']])
}
});
});
})
</script>
I would do it somehow like that:
// Your data
let dataArray = [{data: 1, otherData: 2, elseData: 3}]
// The element, where you want to show it
let targetElement = document.getElementById('your-targer-id');
// The container element for elements
let newContainer = document.createElement('ul');
// Pure JS loop, easy to understand what is happening
// But you can also do it with .map();
for (let i = 0; i < dataArray.length; i++) {
// Add every line
newContainer.innerHTML+='<li>' + dataArray[i].data + '</li>';
// Or other things, depending how you want to show the data
newContainer.innerHTML+='<li> data value is: ' + dataArray[i].data + ' and otherData value is: ' + dataArray[i].otherData + '</li>'; //etc
}
// Append created list in target element
targetElement.appendChild(newContainer);
EDIT - now I see, that you want to display multiple values in text input, rather like so:
let dataArray = [...your-data-array]
let targetElement = document.getElementById('target-input');
for (let i = 0; i < dataArray.lenght; i++) {
// loop throug elements and add it to value attribute of input, separated by coma.
targetElement.value+=dataArray[i].expected_values + ', ';
}

Firebase - Prevent child_added when delete with limitToLast

i want to build mini webchat - When view site i set show 5 messages and if view more, you can click button. All things are fine but when i remove 1 node, firebase auto add last node into, how can i prevent it?
Ex: I have node A,B,C,D,E,F,G. I had loaded list C,D,E,F,G but when i delete 1 in all, it auto add B into list.
<div id="messgesDiv">
<center><h3>Message</h3></center>
</div>
<div style="margin-top: 20px;">
<input type="text" id="nameInput" placeholder="Name">
<input type="text" id="messageInput" placeholder="Message" data-id="">
<input type="text" id="idproject" placeholder="ID Project">
</div>
<button id="delete">Delete Test</button>
<button id="edit">Edit</button>
<button id="loadmore">Load more</button>
<button id="showlastkey">Show last key</button>
My javascript
$('#loadmore').click(function() {
i = 0; old = first;
myDataRef.orderByKey().endAt(first).limitToLast(6).on('child_added', function (snapshot){
if( i == 0)
first = snapshot.key();
var message = snapshot.val();
if(snapshot.key() != old)
displayChatMessage(message.name, message.text, message.idproject, 'old');
i++;
console.log('myDataRef.orderByKey().endAt(first).limitToLast(6)');
});
});
$("#messageInput").keypress(function (e){
if(e.keyCode == 13){ //Enter
var name = $("#nameInput").val();
var text = $("#messageInput").val();
var idproject = $("#idproject").val();
if($("#messageInput").data("id")=='')
{
myDataRef.push({name: name, text: text, idproject: idproject});
}
else
{
myDataRef.child(key).update({name: name, text: text, idproject: idproject});
$('#messageInput').attr('data-id', '');
}
$("#messageInput").val("");
}
});
myDataRef.limitToLast(5).on('child_added', function (snapshot){
if( i == 0)
first = snapshot.key();
var message = snapshot.val();
displayChatMessage(snapshot.key(), message.name, message.text, message.idproject, 'new');
i++;
console.log(snapshot.key());
console.log(' myDataRef.limitToLast(5)');
});
function displayChatMessage(key, name, text, idproject, status){
//console.log(name + " -- " + text + " -- " +idproject);
if( status == 'new')
{
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).appendTo($("#messgesDiv"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
else
{
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).insertAfter($("center"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
}
$('#delete').click(function() {
myDataRef.child(key).remove();
$('#messgesDiv').filter('[data-id="'+key+'"]').remove();
});
Firebase limit queries act like a view on top of the data. So if you create a query for the 5 most recent messages, the Firebase client will ensure that you always have the 5 most recent messages.
Say you start with these messages:
message1
message2
message3
message4
message5
Now if you add a message6, you will get:
child_removed message1
child_added message6
So that your total local view becomes:
message2
message3
message4
message5
message6
Conversely when you remove message 6 again, you get these events:
child_removed message6
child_added message1 (before message2)
So that you can update the UI and end up with the correct list again.
There is no way to change this behavior of the API. So if you want to handle the situation differently, you will have to do this in your client-side code.
Your code currently only handles child_added. If you have add a handler for child_removed you'll see that you can easily keep the user interface in sync with the data.
Alternatively you can detect that the message is already in your UI by comparing the key of the message you're adding to the ones already present in the DOM:
function displayChatMessage(key, name, text, idproject, status){
var exists = $("div[data-id='" + key + "']").length;
if (status == 'new' && !exists) {
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).appendTo($("#messgesDiv"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
else {
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).insertAfter($("center"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
}

How can I retrieve result from my country in here maps?

I use this function to retrieve results of the user search of a destination, but this gets all results from the world, how can I distinct results from certain country
function getPlace() {
setLoadingIcons(true);
var places = platform.getPlacesService(),
entryPoint = H.service.PlacesService.EntryPoint,
txtSearch = document.getElementById('txtSearch');
places.request(entryPoint.SEARCH, { 'at': _HEREmap.getCenter().lat + ',' + _HEREmap.getCenter().lng, 'q': txtSearch.value, 'size': 5 }, function (response) {
var items = response.results.items;
var placeHTML = '<div> <input hidden name="lat" value="{LAT}"><input hidden name="lat" value="{LNG}">{TITLE} <img src="Images/navigation Icon.png" id="arr" width="15" /> </div>';
var html = '';
for (var i = 0; i < items.length; i++) {
html += placeHTML.replace("{TITLE}", items[i].title).replace("{LAT}", items[i].position[0]).replace("{LNG}", items[i].position[1]);
}
document.getElementById('divSearchResult').innerHTML = html + '<div id="divCnclBtn"><img src="Images/Cancel Button.png" id="cnclBtn" onclick="onSearchTextBlur();"></div>';
document.getElementById('divSearchResult').style['display'] = 'block';
setLoadingIcons(false);
}, function (resp) {
//console.log('ERROR: ' + resp);
setLoadingIcons(false);
});
}
So, from what I can tell in the Places API reference, it's surprisingly hard to do...
First, instead of 'at' use 'in' with a bounding box (i.e. the bounding box of the country) to get rough filtering to work.
When you get results, look at each place result's address property and filter them by address.country (or address.countryCode).

New to JavaScript - Need help creating multiple objects with data from a form

I just started learning JavaScript and have been stuck on an assignment for about a week now, I've tried several solutions but every time I add something I break something else.
The assignment is to create a form (which I have completed). The form is to be used to enter data for a new favorite item, when each item is entered it should be displayed on the page and in the console log, as additional items are entered they are added to the list and all items are displayed -
Ex - Favorites are: URL:http://oriellyschool.com, title: O'Reilly School, comment: help, tags: school, learning, URL: http://google.com, title: Google, comment: Use google to find info on JavaScript, tags: search, finding info faves:html:133
The specific instructions are to use objects for both all favorites and each new favorite item. The functionality to display the favorites (in console and on page) should be included in the methods for the objects.
I am able to get the data from the form into a function and had the function to create the favorites working yesterday, not sure what happened this morning.
If someone could please take a look at this and tell me if I am at least heading in the right direction I would appreciate it. I'm just going in circles now. (I have tons of console.log statements in the code so I could try to see what it was doing).
Thanks!
Code:
// Function to create entries for favorite items from web form
function FaveoriteEntry(url, title, comment, tags) {
console.log("In Fave Function");
this.url = url;
console.log(this.url);
this.title = title;
console.log(this.title);
this.comment = comment;
console.log(this.comment);
this.tags = tags;
console.log(this.tags);
console.log("Have all items");
}
//Function to retrieve data from web form and send to function to creat favorite
//object.
function addFavorite() {
var myFavorites = [];
console.log("In Function");
var furl = getFavorites.formURL.value;
var ftitle = getFavorites.formTitle.value;
var fcomment = getFavorites.formComment.value;
var ftags = getFavorites.formTags.value;
this.clear = getFavorites.reset();
console.log("Entry: " + furl + " " + ftitle + " " + fcomment + " " + ftags);
this.createFavorites = function(url, title, comment, tags) {
console.log("In Fave Function");
this.url = url;
console.log(this.url);
this.title = title;
console.log(this.title);
this.comment = comment;
console.log(this.comment);
this.tags = tags;
console.log(this.tags);
console.log("Have all items");
this.string = (this.url + "," + this.title + "," + this.comment + "," +
this.tags);
myFavorites.push(this.string);
var addfavorite = new this.createFavorites(furl, ftitle, fcomment,
ftags);
console.log(myFavorites);
}
}
body {
font-family: Helvetica, Ariel, sans-serif;
}
form {
display: table;
border-spacing: 5px;
}
form p {
display: table-row;
}
form label {
display: table-cell;
text-align: right;
}
form input {
display: table-cell;
}
span.comment {
font-size: 80%;
color: #777777;
}
span.tags {
font-size: 80%;
color: rgb(48, 99, 170);
}
<!doctype html>
<html>
<head>
<title>Advanced JavaScript Project: Favorites and Tags</title>
<meta charset="utf-8">
</head>
<body>
<form name="getFavorites" onsubmit="return favorites(this)">
<h1>Tag and save your favorites</h1>
<text></text>
<fieldset>
<legend>Add a new favorite:</legend>
<p>
<label>URL:</label>
<input type="text" name="formURL" value="" />
<p>
<label>Title:</label>
<input type="text" name="formTitle" value="" />
</p>
<p>
<label>Comment:</label>
<input type="text" name="formComment" value="" />
</p>
<p>
<label>Tags:</label>
<input type="text" name="formTags" value="" />
</p>
<input type="button" name="button" value="Add Link" onClick="addFavorite(this.form)" />
</fieldset>
<u1 id="faves-lists">
<h1> List of Favorites</h1>
<li>Test -</li>
<p> <span class="comments"></span>
</p>
<p> <span class="tags"></span>
</p>
</u1>
</form>
</body>
</html>
put this:
var addfavorite = new this.createFavorites(furl, ftitle, fcomment,
ftags);
console.log(myFavorites);
out side of createFavorites function.like this:
function addFavorite() {
var myFavorites = [];
console.log("In Function");
var furl = getFavorites.formURL.value;
var ftitle = getFavorites.formTitle.value;
var fcomment = getFavorites.formComment.value;
var ftags = getFavorites.formTags.value;
this.clear = getFavorites.reset();
console.log("Entry: " + furl + " " + ftitle + " " + fcomment + " " + ftags);
this.createFavorites = function(url, title, comment, tags) {
console.log("In Fave Function");
this.url = url;
console.log(this.url);
this.title = title;
console.log(this.title);
this.comment = comment;
console.log(this.comment);
this.tags = tags;
console.log(this.tags);
console.log("Have all items");
this.string = (this.url + "," + this.title + "," + this.comment + "," +
this.tags);
myFavorites.push(this.string);
}
var addfavorite = new this.createFavorites(furl, ftitle, fcomment,
ftags);
console.log(myFavorites); // result here
}

Categories

Resources