Fetch data from excel sheet using Javascript - javascript

I am using following code to extract data from excel sheet using javascript. This is working good and after opening the HTML page, getting the data that I want and closing the page, I am unable to open and edit the excel sheet as it is throwing the exception, "File already held by the user and unable to be edited". Is there anyway to handle the closing of excel sheet at the end of the code? Please help me.
<!DOCTYPE html>
<html>
<body>
Enter Salomon account:<br>
<input type="text" id="myText" name="SalAccount">
<br>
<button onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script language="javascript" >
function myFunction()
{
alert("hello");
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:/Users/bv15457/Desktop/test1.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var x = document.getElementById("myText").value;
var lo = 1;
var hi = 682220;
var mid;
var element;
var Flag = 0;
while(lo <= hi && Flag != 1)
{
mid = Math.floor((lo + hi) / 2, 10);
element = excel_sheet.Cells(mid,1).Value;
if (element < x)
{
lo = mid + 1;
}
else if (element > x)
{
hi = mid - 1;
}
else
{
document.getElementById("demo").innerHTML = excel_sheet.Cells(mid,2).Value;
Flag = 1;
}
}
if (Flag != 1)
{
alert("Account is not found in XREF file");
}
}
</script>
</body>
</html>

Related

JS get random value from array and update array

I need your help on this!
I'm generating an array which corresponds to a question number.
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
then I use this number to append the corresponding question, answer then click.
Then I'm getting a new value from the array like this
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
It works and a new question is charged but the array is still the same.
I've tried this
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
But It doesn't work ;-(
Thanks a lot for your help.
Nicolas
Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>
Nicolas, this is the sort of thing you should end up with:
// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;
// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
availableQuestions.length = 0;
for (let i = 1; i <= 10; i++) {
availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
}
}
// Pick a random question and display that to the user
function getRandomQuestion() {
let osQuestions = availableQuestions.length;
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
// If there are no more questions, stop
if (osQuestions == 0) {
qnElement.innerHTML = "Finished!";
qElement.innerHTML = "";
sButton.style.display = "none";
rButton.style.display = "inline";
} else {
// display a sequential question number rather than the actual question number
counter++;
rnd = getRandomNumber(0, osQuestions - 1);
let thisQuestion = availableQuestions[rnd];
qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
qElement.innerHTML = thisQuestion.question;
}
}
// Process the user's answer and remove the question from the array
function submitAnswer() {
// ALSO Add in what needs to be done to update backend database etc when the user clicks submit
availableQuestions.splice(rnd, 1);
getRandomQuestion();
}
// Reset everything - for testing purposes only
function restart() {
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
qnElement.innerHTML = "";
qElement.innerHTML = "";
sButton.style.display = "inline";
rButton.style.display = "none";
// Reset the displayed question number counter
counter = 0;
createQuestions();
getRandomQuestion();
}
// Needed to populate the array and display the first question
function runsetup() {
createQuestions();
getRandomQuestion();
}
window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>
<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>
I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working
Nicolas, this is what I think you should be doing:
// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}
// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);
// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)
// Present the question to the user on the page
// The user completes question and clicks "Submit"
// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);

Is there a function to search an intranet website?

I am a bit new to JavaScript, and just want to search my website for a particular string of text and find it, list it or whatever.
I looked at this solution:
Javascript Search Engine (Search own site)
But am not getting what I want out of it. I'm sure my syntax from HTML to JavaScript is a bit off. I am happy to search the current page for now, but will ultimately want to span across all HTML pages, which are all in a single directory.
Here is my code, and it does not error, but it also does not appear to do anything except clear the textbox.
I have gone through a plethora of examples using W3Schools and some other textbooks on Safari
<!DOCTYPE HTML>
<head>
<style>
</style>
</head>
<body>
<br>
<input type="number" id="str">
<button onclick="findInPage(str.value)">Search</button>
<script language=JavaScript>
var NS4 = (document.layers);
var IE4 = (document.all);
var win = window;
var n = 0;
function findInPage(str) {
var txt, i, found;
if (str == "")
return false;
if (NS4) {
if (!win.find(str))
while(win.find(str, false, true))
n++;
else
n++;
if (n == 0)
alert("Not found.");
}
if (IE4) {
txt = win.document.body.createTextRange();
for (i = 0; i <= n && (found = txt.findText(str)) != false; i++) {
txt.moveStart("character", 1);
txt.moveEnd("textedit");
}
if (found) {
txt.moveStart("character", -1);
txt.findText(str);
txt.select();
txt.scrollIntoView();
n++;
}
else {
if (n > 0) {
n = 0;
findInPage(str);
}
else
alert("Sorry, we couldn't find. Try again");
}
}
return false;
}
</script>
</body>
</HTML>

Calling a JavaScript function in HTML?

I'm extremely new to JavaScript and HTML so go easy on me. I'm attempting to call a function from my external JavaScript file in my HTML file, but nothing I seem to do allows it to work.
JavaScript Code
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength = false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x <= passlength;){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<script type="text/javascript" src="PassGen.js"></script>
<script>
var x = prompt("Enter password length: ")
function generatePassword(x);
</script>
</body>
</html>
The goal is for the user to be prompted to input a password length, then generate a random password which will be alerted to the user and written on screen. However, only the header at the top of the screen is printed.
(I realize that I could just take the function out of the JavaScript file and run it normally, but I kinda wanna leave it like this so I know what to do in the future if I ever run into this situation again.)
Following is the code with Javascript inside <script> tag within HTML document. One thing you should be careful of while writing your javascript code in the HTML file is, to include your javascript code just before the ending tag of body </body>. so it get executed only when your html file is loaded. But if you add your javascript code in the starting ot html file, your JS code will be executed before the file is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
<script>
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
</script>
</body>
</html>
And if you want to have your Javascript code in a separate file, which can be helpful in big programs, then you need to reference that file using <script> tag and this is the way you write it down.
var PasswordLength = false;
var password = "";
var passwordChoice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = prompt("Enter password length: ");
var pass = document.getElementById("password");
generatePassword(input);
function generatePassword(passLength){
while (PasswordLength == false){
if (passLength >= 8){
for(var x = 0; x < passLength;x++){
var randomNum=Math.floor(Math.random()*passwordChoice.length+1);
password = password + passwordChoice.charAt(randomNum);
}
PasswordLength = true;
}
else {
passLength = prompt("Password Length must be 8 characters long.");
}
}
pass.innerHTML = password;}
<!DOCTYPE html>
<html>
<head>
<title>Generate Password</title>
<script src=""></script>
</head>
<body>
<h1 align="center">Password Generated will be displayed here</h1>
<p id="password" align="center"></p>
</body>
</html>
In your code there are the following problems :
1) Change function generatePassword(x); to generatePassword(x.length);
2) Change trueLength = false to trueLength === false
3) Change for(var x = 0; x <= passlength;){ to for(var x = 0; x < passLength; x++){
passlength => passLength , x<= to x< , insert x++
4) Change Math.floor(Math.random()*things.length+1); to Math.floor(Math.random()*(things.length)+1)
5) insert passLength = passLength.length; to else
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var input = document.getElementById("len");
var x = prompt("Enter password length: ")
generatePassword(x.length);
function generatePassword(passLength){
// Check to see if selected length is at least 8 characters long
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
passLength = passLength.length;
}
}
// Select random character from things and add to password until desired length is reached.
for(var x = 0; x < passLength; x++){
var randomNum=Math.floor(Math.random()*(things.length)+1);
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
You can use this code with less complexity :
var trueLength = false, password = "" ;
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
var x = prompt("Enter password length: ")
generatePassword(x);
var input = document.getElementById("len");
function generatePassword(passLength){
while ( passLength.length < 9 )
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
for ( var x = 0; x < passLength.length ; x++ ) {
var randomNum = Math.floor ( Math.random() * (things.length)+1 );
password = password + things.charAt(randomNum);
}
alert("Your password is: " + password);
document.write("<h1>Your Password</h1><p>" + password + "</p>");
}
<h1 align="center">Password Generator</h1>
Few things. In order to have something show up in HTML, you will need to select an HTML element in JavaScript. Next, you used 'passlength' instead of 'passLength' in the for loop. Third, when you write function generatepassword it is invalid syntax as Lux said. Lastly, your for loop doesn't go anywhere because you don't have a third expression. Which should be changed to
for(var x = 0; x <= passLength;x++)
Edit: Another thing I forgot was trueLength = false should be changed to trueLength == false or trueLength === false.
With all that said, here's my solution:
<!DOCTYPE html>
<html>
<head>
<title>Password Generator</title>
</head>
<body>
<h1 align="center">Password Generator</h1>
<p align="center"></p>
<!--script type="text/javascript" src="PassGen.js"></script-->
<script>
var trueLength = false;
var password = "";
var things = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+;':,./<>?";
//var input = document.getElementById("len");
var ppass = document.querySelector("p");
function generatePassword(passLength){
while (trueLength == false){
if (passLength > 8){
trueLength = true;
} else {
passLength = prompt("Password Length must be at least 8 characters long! Please try again. ");
}
}
for(var x = 0; x <= passLength;x++){
var randomNum=Math.floor(Math.random()*things.length+1);
password = password + things.charAt(randomNum);
}
//alert("Your password is: " + password);
//document.write("<h1>Your Password</h1><p>" + password + "</p>");
ppass.textContent = password;}
var x = prompt("Enter password length: ")
generatePassword(x);
</script>
</body>
</html>
What I added was a <p> tag to display the password once it's generated. I use textContent to display it once the password is done generating. And i use document.querySelector to access it.

GoogleApp script. Google calendar script that display current day events

I have some questions regarding google calendar script that I'm building. So I managed to write the script and deploy it as a web app, but I encountered some problems:
1) It should list all current day events, but it lists only one event of the day
2) Also I want to display only the title of the event (it’s working now) and the start time and end time of the event. I managed to display a title (events[i].summary) and the start time of the event, but I was unable to display end time of the event and to change the format of the time that it would display time like this for example : 1pm – 2 pm.
3) Also what I want to do is to make the script run without pressing a button. I want it to work every time I open the published web app or refresh the web app page.
Here is the script code:
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp');
}
function listEvents() {
var actualDate = new Date();
var endOfDayDate = new
Date(actualDate.getFullYear(),actualDate.getMonth(),actualDate.getDate(),23,59,59);
var calendarId = 'primary';
var optionalArgs = {
timeMin: (new Date()).toISOString(),
timeMax: endOfDayDate.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: 'startTime'
};
var response = Calendar.Events.list(calendarId, optionalArgs);
var events = response.items;
var allEvents = [];
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
allEvents.push(events[i].summary + ' ' + events[i].start.dateTime);
}
return allEvents;
} else {
return ['No events found'];
}
And this is a HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Calendar App</h1>
<button onclick="listEvents()">List events</button>
<ul id='events'></ul>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(response){
var events = response;
for(var i = 0; i < events.length; i++) {
document.getElementById('events').innerHTML = '<li>' + response[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
</script>
</body>
</html>
This is the link to actual google scritp: Google Script
Thank you in advance for your help :)
Here is your modified (and working) code. You don't need to use advanced Calendar API since everything you need is available in CalendarApp, including a convenient getEventsForDay().
It shows all your events on opening as required.
code :
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp').setTitle('CalendarApp');
}
function listEvents() {
var today = new Date();
var cal = CalendarApp.getDefaultCalendar();
var events = cal.getEventsForDay(today);
var data = [];
data.push("Events for today "+Utilities.formatDate(today,Session.getScriptTimeZone(),"MMM dd yyyy"));
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
data.push(events[i].getTitle()+' : '+Utilities.formatDate(events[i].getStartTime(),Session.getScriptTimeZone(),"HH:mm")+' - '+Utilities.formatDate(events[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
}
return data;
} else {
return ['No events found','',''];
}
}
html & script :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style="font-family:arial,sans;font-size:12pt">
<h2>Calendar App</h2>
<div id="events">
</div>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(events){
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<p>' + events[0] + '</p>';
for(var i = 1; i < events.length; i++) {
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<li>' + events[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
window.onload = listEvents();
</script>
</body>
</html>
Here's a function I use to get my calendar events for the next 5 weeks. And I use it in conjunction with a webapp so it gets returned to a statement that looks like this document.getElementById('hotbox').innerHTML=hl; hotbox is just a div.
function getMyEvents()
{
var allCals=CalendarApp.getAllCalendars();
var s=Utilities.formatString('<strong>%s</strong>',Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"E MMM d, yyyy HHmm"))
var min=60 * 1000;
var hr=60 * min;
var day=24 * hr;
var wk=7 * day;
var start = new Date(new Date().setHours(0,0,0));
var end=new Date(start.valueOf() + (5 * wk));//you could make this + day instead of + (5 * wk)
var incl=['Calendar1Name','Calendar2Name'];//These are different calendar names as I have some special calendars for different functions
for(var i=0;i<allCals.length;i++)
{
if(incl.indexOf(allCals[i].getName())>-1)
{
s+=Utilities.formatString('<br /><strong>%s</strong>',allCals[i].getName());
var events=allCals[i].getEvents(start, end);
if(events)
{
s+='<br><ul>';
for(j=0;j<events.length;j++)
{
var calId=allCals[i].getId();
var evId=events[j].getId();
if(events[j].isAllDayEvent())
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s %s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),'All Day',Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d"),calId,evId);
}
else
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d, HHmm"),calId,evId);
}
}
s+='</ul>';
}
}
}
s+='<br /><input type="button" value="Delete Selected Events" onClick="delSelectedEvents();" style="width:250px;height:35px;text-align:center;margin:10px 0 10px 0;" />';
//var ui=HtmlService.createHtmlOutput(s);
//SpreadsheetApp.getUi().showModelessDialog(ui, 'My Events');
return s;
}

Using Google Scripts to search and to match array

I want to build button with a dialog box to match the result using script. For example, I divided US into East, Middle and West. I have a text file named US 50 states name and abbreviation. When I type "NY" or Boston", the result would show "East". How can I achieve this in Google Spreadsheet.Thanks.
This is the script file:
function findSection(state)
{
var state =(typeof(state) != 'undefined')?state: '';
var found = "No Data Provided";
if(state)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getSheetByName('StateSearch');
var rng = sht.getDataRange();
var rngA = rng.getValues();
found ='Not Found';
for(var i=1;i<rngA.length;i++)
{
if((state==rngA[i][0]) || (state == rngA[i][1]))
{
found = rngA[i][2];
break;
}
}
}
return found;
}
function searchSideBar()
{
var ui = HtmlService.createHtmlOutputFromFile('sectionSearchDialog').setTitle('State Search');
SpreadsheetApp.getUi().showSidebar(ui);
}
This is the HTML file for the sidebar:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
State:<input type="text" id="txt1" size="30" value=""/><br />
Section:<input type="text" id="txt2" size="30" value=""/><br />
Search:<input type="button" value="Search" onClick="sectionSearch();" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
console.log('here');
function sectionSearch()
{
var v = $('#txt1').val();
google.script.run
.withSuccessHandler(updateSection)
.findSection(v);
}
function updateSection(v)
{
$('#txt2').val(v);
}
</script>
</body>
</html>
This is what the Spreadsheet "StateSearch' looks like: you can put the state data here and in the third column you can add your section names if you wish. Adding the cities is left as an exercise for the reader.
A simple way to add some cities without Geo Location might be this way:
Same sidebar code: this script file:
function findSection(state)
{
var state =(typeof(state) != 'undefined')?state: '';
var found = "No Data Provided";
if(state)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getSheetByName('StateSearch');
var rng = sht.getDataRange();
var rngA = rng.getValues();
found ='Not Found';
for(var i=1;i<rngA.length;i++)
{
if((state==rngA[i][0]) || (state == rngA[i][1]) || (isACity(state,rngA[i][3])>-1))
{
found = rngA[i][2];
break;
}
}
}
return found;
}
function searchSideBar()
{
var ui = HtmlService.createHtmlOutputFromFile('sectionSearchDialog').setTitle('State Search');
SpreadsheetApp.getUi().showSidebar(ui);
}
function isACity(city,cities)
{
var city = (typeof(city) != 'undefined')?city:'';
var cities = (typeof(cities) != 'undefined')?cities:'';
var r = -1;
if(city && cities)
{
var citiesA = String(cities).split(',');
r = citiesA.indexOf(city);
}
return r;
}
The spreadsheet looks like this:
You have to run the sidebar code to load it or you can do that in an onOpen().

Categories

Resources