I am trying to make a google script web app that takes input from an HTML form and passes the input to a script. Right now, the function is failing because document.getelementbyId('text') returns null instead of the actual form value. How can I fix this?
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit() {
var formObject = document.getElementById('text');
google.script.run.withSuccessHandler(setTable).getSportData(formObject);
console.log(formObject);
}
function setTable(data) {
var div = document.getElementById('output');
div.innerHTML = createTable(data);
}
/**
* Adds an html table
*/
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit()">
<input name="text" type="text" />
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
Code.gs
//Initalization of global variables for use by the script's custom functions
var ss = SpreadsheetApp.openById("spreadsheetID");
var sheet = ss.getSheetByName("Sheet1");
var sportsFromSheet = sheet.getRange("D4:D12");
var namesFromSheet = sheet.getRange("B4:B12").getValues();
var timesFromSheet = sheet.getRange("A4:A12").getValues();
var NAMES = [];
var TIMES = [];
/**
* Handles HTTP GET requests to the published web app.
* #return {HtmlOutput} The HTML page to be served.
*/
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
/**
* Gets both names and Times of checked-in people from the spreadsheet from the private function getOutput.
* #return {HtmlOutput} A 2D array containing the names and times.
*/
function getSportData(formObject) {
getNamesInSport(formObject);
getTimesInSport(formObject);
var OUTPUT = [
[NAMES],
[TIMES]
];
return OUTPUT;
}
//Puts the names of every person from an inputted sport into an array.
function getNamesInSport(input) {
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i++) {
if(data[i] == input){
NAMES.push(namesFromSheet[i][0]);
}
}
}
//Puts the times of every person from an inputted sport into an array.
function getTimesInSport(input){
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i ++) {
if(data[i] == input){
TIMES.push(timesFromSheet[i][0]);
}
}
}
Duplicate of Why does jQuery or a DOM method such as getElementById not find the element?.
You appear to have answered your own question.
document.getElementById('text') returns null because...
You don't have an element with an id="text".
document.getElementById will return null
if an element with the specified ID is not in the document. (Mozilla Developer Network)
The solution, is <input type="text" name="text" id="text">
Related
I hope everyone is in good health health and condition.
Recently, I have been working on Google Docs hyperlinks using app scripts and learning along the way. I was trying to get all hyperlink and edit them and for that I found an amazing code from this post. I have read the code multiple times and now I have a good understanding of how it works.
My confusion
My confusion is the recursive process happening in this code, although I am familiar with the concept of Recursive functions but when I try to modify to code to get only the first hyperlink from the document, I could not understand it how could I achieve that without breaking the recursive function.
Here is the code that I am trying ;
/**
* Get an array of all LinkUrls in the document. The function is
* recursive, and if no element is provided, it will default to
* the active document's Body element.
*
* #param {Element} element The document element to operate on.
* .
* #returns {Array} Array of objects, vis
* {element,
* startOffset,
* endOffsetInclusive,
* url}
*/
function getAllLinks(element) {
var links = [];
element = element || DocumentApp.getActiveDocument().getBody();
if (element.getType() === DocumentApp.ElementType.TEXT) {
var textObj = element.editAsText();
var text = element.getText();
var inUrl = false;
for (var ch=0; ch < text.length; ch++) {
var url = textObj.getLinkUrl(ch);
if (url != null) {
if (!inUrl) {
// We are now!
inUrl = true;
var curUrl = {};
curUrl.element = element;
curUrl.url = String( url ); // grab a copy
curUrl.startOffset = ch;
}
else {
curUrl.endOffsetInclusive = ch;
}
}
else {
if (inUrl) {
// Not any more, we're not.
inUrl = false;
links.push(curUrl); // add to links
curUrl = {};
}
}
}
if (inUrl) {
// in case the link ends on the same char that the element does
links.push(curUrl);
}
}
else {
var numChildren = element.getNumChildren();
for (var i=0; i<numChildren; i++) {
links = links.concat(getAllLinks(element.getChild(i)));
}
}
return links;
}
I tried adding
if (links.length > 0){
return links;
}
but it does not stop the function as it is recursive and it return back to its previous calls and continue running.
Here is the test document along with its script that I am working on.
https://docs.google.com/document/d/1eRvnR2NCdsO94C5nqly4nRXCttNziGhwgR99jElcJ_I/edit?usp=sharing
I hope you will understand what I am trying to convey, Thanks for giving a look at my post. Stay happy :D
I believe your goal as follows.
You want to retrieve the 1st link and the text of link from the shared Document using Google Apps Script.
You want to stop the recursive loop when the 1st element is retrieved.
Modification points:
I tried adding
if (links.length > 0){
return links;
}
but it does not stop the function as it is recursive and it return back to its previous calls and continue running.
About this, unfortunately, I couldn't understand where you put the script in your script. In this case, I think that it is required to stop the loop when links has the value. And also, it is required to also retrieve the text. So, how about modifying as follows? I modified 3 parts in your script.
Modified script:
function getAllLinks(element) {
var links = [];
element = element || DocumentApp.getActiveDocument().getBody();
if (element.getType() === DocumentApp.ElementType.TEXT) {
var textObj = element.editAsText();
var text = element.getText();
var inUrl = false;
for (var ch=0; ch < text.length; ch++) {
if (links.length > 0) break; // <--- Added
var url = textObj.getLinkUrl(ch);
if (url != null) {
if (!inUrl) {
// We are now!
inUrl = true;
var curUrl = {};
curUrl.element = element;
curUrl.url = String( url ); // grab a copy
curUrl.startOffset = ch;
}
else {
curUrl.endOffsetInclusive = ch;
}
}
else {
if (inUrl) {
// Not any more, we're not.
inUrl = false;
curUrl.text = text.slice(curUrl.startOffset, curUrl.endOffsetInclusive + 1); // <--- Added
links.push(curUrl); // add to links
curUrl = {};
}
}
}
if (inUrl) {
// in case the link ends on the same char that the element does
links.push(curUrl);
}
}
else {
var numChildren = element.getNumChildren();
for (var i=0; i<numChildren; i++) {
if (links.length > 0) { // <--- Added or if (links.length > 0) break;
return links;
}
links = links.concat(getAllLinks(element.getChild(i)));
}
}
return links;
}
In this case, I think that if (links.length > 0) {return links;} can be modified to if (links.length > 0) break;.
Note:
By the way, when Google Docs API is used, both the links and the text can be also retrieved by a simple script as follows. When you use this, please enable Google Docs API at Advanced Google services.
function myFunction() {
const doc = DocumentApp.getActiveDocument();
const res = Docs.Documents.get(doc.getId()).body.content.reduce((ar, {paragraph}) => {
if (paragraph && paragraph.elements) {
paragraph.elements.forEach(({textRun}) => {
if (textRun && textRun.textStyle && textRun.textStyle.link) {
ar.push({text: textRun.content, url: textRun.textStyle.link.url});
}
});
}
return ar;
}, []);
console.log(res) // You can retrieve 1st link and test by console.log(res[0]).
}
I am a teacher and need to create lots of multiple choice quizzes like this for my students.
You will see that each multiple choice question has exactly the same format - a question to be uploaded as an image and then followed by 4 multiple choice options - A, B, C and D.
My question is, is there any way to automate this process?
Each batch of questions are inside a googledrive folder and are named '1.png', '2.png', '3.png', etc - these are to be uploaded as images on the google form.
In a separate folder, I have a googlesheet listing all the answers to each question, it looks like this.
So the numbers that match with the answers (letters) in the spreadsheet correspond to the image files (eg. the first row of the spreadsheet above shows that the answer to question 1.png is A)
In a separate folder, I have another googlesheet, with feedback for both incorrect and correct answers which looks like this. Not all questions have feedback.
Is there anyway to automatically generate quizzes from these googlesheets and png files?
Thanks for taking the time to read through all this, and special thanks if you are able to suggest a solution?
Here's a solution to a questioner that wanted to randomly select a given number of questions from a question bank. This doesn't utilize google forms but rather it uses html forms.
Here's the code (your welcome to adapt it):
I had some questions on the code and corrected and problem and went in and updated the code. It's a little more organized and a bit easier to follow...I hope.
Code.gs:
function onOpen() {
SpreadsheetApp.getUi().createMenu('Questions Menu')
.addItem('Questions', 'launchQuestionsDialog')
.addToUi();
}
question.gs
function getQuestions() {
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qnum=cpData.qNum;
var qa=getQAndA();
var qi=getAnswerIndexes();
var html='';
var clr=['#f6d1ac','#c5e9bd'];
for(var i=0;i<qa.length;i++) {
html+=Utilities.formatString('<div id=d%s style="font-weight:bold;background-color:%s;padding:5px;"><span id="q%s">%s</span><input type="hidden" value="%s" class="hiding" />',qa[i][0],clr[i % 2],qa[i][0],qa[i][1],qa[i][0]);
html+=Utilities.formatString('<input type="hidden" value="%s" class="hiding" />',qa[i][0]);
for(var j=qi.firstIdx;j<=qi.lastIdx;j++) {
if(qa[i][j]) {
html+=Utilities.formatString('<br /><input type="radio" name="n%s" value="%s" />%s',qa[i][0],qa[i][j],qa[i][j]);
}
}
html+='</div>'
}
html+='<div id="controls"><br /><input type="button" value="Submit" onClick="recordData();" /></div>';
return {html:html}
}
function launchQuestionsDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('questions').setWidth(800).setHeight(500);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The new Questions");
}
function selectTest() {
var qA=selectQuestions(5,24);
Logger.log(qA);
}
function selectQuestionIndexes(n,m) {
var set=[];
do {
var i=Math.floor(Math.random()*(m));
if(set.indexOf(i)==-1) {
set.push(i);
}
}while(set.length<n);
return set;
}
function getCpData() {
var ss=SpreadsheetApp.getActive();
var cpSh=ss.getSheetByName('ControlPanel');
var cpRg=cpSh.getDataRange();
var cpVa=cpRg.getValues();
var qsrcSh=ss.getSheetByName(cpVa[1][0]);
var adesSh=ss.getSheetByName(cpVa[1][1]);
var qnum=cpVa[1][2];
var cpData={'qSrc':cpVa[1][0],'aDes':cpVa[1][1],'qNum':cpVa[1][2]};
return cpData;
}
function getAnswerIndexes() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(getCpData().qSrc);
var rg=sh.getRange(1,1,1,sh.getLastColumn());
var vA=rg.getValues();
var re=/Answer \d{1,2}/i;
var fidx=0;
var lidx=0;
var first=true;
vA[0].forEach(function(e,i){if(String(vA[0][i]).match(re))if(first){fidx=i;first=false;}else{lidx=i;}});
return {'firstIdx':fidx,'lastIdx':lidx};
}
function recordData(responses) {
if(responses) {
var ss=SpreadsheetApp.getActive();
var sheetname=getCpData().aDes;
var sh=ss.getSheetByName(sheetname);
var ts=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss");
responses.forEach(function(e,i){e.splice(0,0,ts);sh.appendRow(e)});
}
return true;
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('questions');
}
function getQAndA() {
var qa=[];
var cma=',';
var ss=SpreadsheetApp.getActive();
var cpData=getCpData();
var qsrcSh=ss.getSheetByName(cpData.qSrc);
var qsrcRg=qsrcSh.getRange(2,1,qsrcSh.getLastRow()-1,qsrcSh.getLastColumn());
var qsrcVa=qsrcRg.getValues();
var qs=selectQuestionIndexes(cpData.qNum,qsrcVa.length);
var aIdxs=getAnswerIndexes();
for(var i=0;i<qsrcVa.length;i++) {
var qas='';
if(qs.indexOf(i)>-1) {
qas+=qsrcVa[i][0] + cma + qsrcVa[i][1];
for(j=aIdxs.firstIdx;j<=aIdxs.lastIdx;j++) {
if(qsrcVa[i][j]) {
qas+= cma + qsrcVa[i][j];
}
}
qa.push(qas.split(cma));
}
}
return qa;
}
questions.html:
<!DOCTYPE html>
<html>
<head>
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
google.script.run
.withSuccessHandler(function(hObj){
$('#container').html(hObj.html);
})
.getQuestions();
});
function recordData() {
var responses=[];
var cm=',';
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++) {
var id=divs[i].getAttribute(['id']);
var qnum=$('div#' + id + ' ' + 'input.hiding').val();
//var question=document.getElementById(id).innerHTML;
var question=$('#q' + qnum ).text();
var answer=$('input[name="n' + qnum + '"]:checked').val();
if(id!='controls') {
if(!answer) {
window.alert('You did not answer question number ' + Number(i+1) + '. It is a requirement of this survey that all questions must be answered.' );
return;
}else {
var end='is near';
var s=qnum + cm + question + cm + answer;
responses.push(s.split(cm));
}
}
}
google.script.run
.withSuccessHandler(displayThanks)
.recordData(responses);
}
function displayThanks() {
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++) {
divs[i].style.cssText="display:none;text-align:center";
}
var elemDiv = document.createElement('div');
elemDiv.innerHTML="<br /><h1>Thank You For Your Participation in This Survey</h1>";
document.body.appendChild(elemDiv);
}
console.log('My Code');
</script>
<style>
#reply{display:none;}
#collect{display:block;}
body {
background-image: url("http://myrabridgforth.com/wp-content/uploads/blue-sky-clouds.jpg");
background-color: #ffffff;
background-repeat: no-repeat;
background-position: left bottom;
}
</style>
</head>
<body>
<div id="container">
</div>
</body>
</html>
Here's what the various tabs on the spreadsheet look like:
The ControlPanel Tab:
The QuestionBank Tab:
The Test1 Tab:
Hopefully this will be of some value to you.
To over-come the problem in high densely populated area
ultra dense network is suggested. Ultra dense network
maintain a constant connectivity, data speed in highly
populated area.
This may be a naive question, sorry for that, but I'm trying to sort out a potential concurrency issue. I have a registration procedure which begins with the user selecting their category from a drop down menu. That triggers a query to a particular page in a google sheet where it retrieves an available ID number that is displayed to the user. There are a couple steps required before the final submit button is pressed. This (I think) creates a chance for more than one person to retrieve the same ID. I do use google's lockservice but on the function which writes the form information to my spreadsheet (based on a script of Martin Hawksley). If it was possible to determine how many people were currently viewing the registration page I could use that value in the query with an if statement such that a different row number is retrieved. This would eliminate the chance of duplicates.
Does that sound reasonable? Perhaps there is a much better way.
Any advice would be most appreciated.
If it was possible to determine how many people were currently viewing
the registration page
If you don't want to use Google Analytics. Here is a simple example of how you can poll with a client to maintain a session, and count how many users are active.
NOTE: I threw this together, it could be refactored a bit to be prettier, but it should get the gist of it across
Working Example Open this a couple times, you will see your session IDs in each and a count. Sessions expire after 60 seconds of no activity, and auto-end if you close the page.
Project file structure:
Code.gs
index.html
javascript.html
Apps Script
var sessionTimeout = 60; //60 seconds
//Triggered when the page is navigated to, serves up HTML
function doGet(){
var template = HtmlService.createTemplateFromFile('index');
template.userID = NewSession();
return template.evaluate()
.setTitle('Active Users')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
/*================ Polling ================*/
//Client calls this function to poll, updates cache, returns active users
function ClientPoll(id){
var scriptCache = CacheService.getScriptCache();
UpdateScriptCache(id, 0, scriptCache, true);
var activeIDs = GetActiveIDs(scriptCache);
return activeIDs;
}
function EndSession(id){
var scriptCache = CacheService.getScriptCache();
scriptCache.remove(id);
var activeIDs = GetActiveIDs(scriptCache);
activeIDs.splice(activeIDs.indexOf(id), 1);
UpdateScriptCache('ActiveIDs', activeIDs, scriptCache, false);
}
//Server calls every minute to check for inactive sessions
function CheckForInactiveSessions(){
var scriptCache = CacheService.getScriptCache();
var activeIDs = GetActiveIDs(scriptCache);
var allSessions = scriptCache.getAll(activeIDs);
if(Object.keys(allSessions).length > 0){
var keys = Object.keys(allSessions);
var newActiveIDs = [];
for(var i = 0; i < keys.length; i++){
newActiveIDs.push(keys[i]);
}
Logger.log(keys.length);
UpdateScriptCache('ActiveIDs', newActiveIDs, scriptCache, false);
}
}
/*================ Session Creation & Cache ================*/
//Handles setting up a new session, called when page is opened
function NewSession(){
var id = GenerateUID();
AddNewActiveID(id);
return id;
}
//Gets a list of all active IDs
function GetActiveIDs(scriptCache){
if(!scriptCache){
scriptCache = CacheService.getScriptCache();
}
var active = scriptCache.get('ActiveIDs');
if(active !== null){
return JSON.parse(active);
}
return [];
}
//Adds a new ID to the cache
function AddNewActiveID(id){
var scriptCache = CacheService.getScriptCache();
var activeIDs = JSON.parse(scriptCache.get('ActiveIDs'));
if(activeIDs == null){
activeIDs = [];
}
activeIDs.push(id);
//Update the Active ID List
UpdateScriptCache('ActiveIDs', activeIDs, scriptCache, false);
//Add new ID to cache
UpdateScriptCache(id, 0, scriptCache, true);
}
//Handles updating the Active IDs cache and prevents race conditions or collisions
function UpdateScriptCache(key, data, cache, timeout){
var lock = LockService.getScriptLock();
lock.waitLock(15000);
if(timeout){
cache.put(key, JSON.stringify(data), sessionTimeout);
} else {
cache.put(key, JSON.stringify(data), 21600)
}
lock.releaseLock();
}
/*================ ID Generation ================*/
//Handles generating and returning a new ID
function GenerateUID(){
var generator = new IDGenerator();
var id = generator.generate();
return id;
}
//Generates a random(ish) ID;
function IDGenerator() {
this.length = 10;
this.timestamp = new Date().getTime();
var getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function(){
var timestamp = this.timestamp.toString();
var parts = timestamp.split('').reverse();
var id = '';
for(var i = 0; i < this.length; i++){
var index = getRandomInt(0, parts.length - 1);
id += parts[index];
}
return id;
}
}
JavaScript:
<script>
//Initilization
$(function(){
//Set the users ID in HTML
$('#userID').text(userID);
//Setup handler to end the session before the page closes
$(window).bind('beforeunload', function(){
EndSession();
});
//Start the timer
var deadline = new Date(Date.parse(new Date()) + 5000);
initializeTimer('pollingIn', deadline);
});
//Polls the server to update session and get active users
function PollServer(){
console.log('Polling server');
google.script.run.withSuccessHandler(UpdateActiveUsers).ClientPoll(userID);
var deadline = new Date(Date.parse(new Date()) + 5000);
initializeTimer('pollingIn', deadline);
}
//Ends the session right before the page closes
function EndSession(){
google.script.run.withSuccessHandler().EndSession(userID);
}
//Updates the active users div
function UpdateActiveUsers(users){
console.log(users)
var userText = '';
for(var i = 0; i < users.length; i++){
if(i == 0){
userText += users[i];
continue;
}
userText += ', ' + users[i];
}
$('#activeUsersCount').text(users.length);
$('#activeUsers').text(userText);
}
//Initilizes the timer
function initializeTimer(id, endtime) {
var timer = $('#'+id);
function updateTimer() {
var time = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((time / 1000) % 60);
timer.text(seconds);
if (time <= 0) {
clearInterval(timeInterval);
PollServer();
}
}
updateTimer();
var timeInterval = setInterval(updateTimer, 1000);
}
</script>
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://ssl.gstatic.com/docs/script/css/add-ons1.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="mainForm">
<h1>Active Users</h1>
<div class="box">
Active Users Count:
<span id="activeUsersCount">0</span>
</div>
<div class="box">
Active Users:
<span id="activeUsers"></span>
</div>
<div class="box">
Polling in:
<span id="pollingIn"></span>
</div>
<div class="box">
You Are:
<span id="userID"></span>
</div>
</div>
<?!= HtmlService.createHtmlOutputFromFile('javascript').getContent(); ?>
<script>
var userID = <?= userID ?>;
</script>
</body>
</html>
<style>
.box {
display: block;
padding: 0.5em;
}
body {
padding: 1em;
}
</style>
I'm trying to make an alert with the value of the selected radio button, but I allways get the first of them, regardless the one I choose...(Acompanhado);
html:
<form/>
<input type="radio" class="simple_form" name="grupo_1" value="Acompanhado" id="saida"/>
<span class="texto">Acompanhado</span>
<input type="radio" class="simple_form" name="grupo_1" value="Individual" id="saida"/>
<span class="texto">Individual</span>
</form>
js:
function save() {
var saida_js = document.getElementById('saida').value;
alert("Tipo de saida: " + saida_js);
}
Any idea ?
#Quentin: I have alot of alerts, cause Im trying to get all data from a form. I used your code, and I get no alert at all.
function save() {
var morada_js = document.getElementById('morada').value;
var data_js = document.getElementById('data').value;
var hora_js = document.getElementById('hora').value;
var radio_saida = document.getElementsByName('name_saida');
var notas_js = document.getElementById('notas').value;
var condicoes_atm_js = document.getElementById('condicoes_atm').value;
alert("Morada: " + morada_js);
alert("Data: " + data_js);
alert("Hora: " + hora_js);
function get_checked_radio(radio_saida) {
for (var i = 0; i < radio_saida.length; i++) {
var current = radio_saida[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radio_saida).value);
alert("Notas: " + notas_js);
}
An id must be unique in a document.
To find the value of a selected radio button in a group, get the group by its nameā¦
var radios = document.getElementsByName('radio_name'); // or
var radios = document.forms.formId.elements.radio_name;
Then loop over them until you find the one with the true checked property.
function get_checked_radio(radios) {
for (var i = 0; i < radios.length; i++) {
var current = radios[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radios).value);
Makes sense because you've got two input tags with the same id saida
I have a code which takes data from google custom search API, There is no wrong with the custom search API part, it retrieves data without any error
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>
Required data are saved in the pageName, pageLink and pageDetails arrays.
Now I want display them with chechboxes and allow user to select them.
I need to take the links of the selected sites(pageLink variable) and pass it to anothe file using POST method
I tried using bellow code just before end of the body tag()
<form action="b.php" method="post">
<script>
for (var j = 0; j < 5; j++) {
document.write("<input type='checkbox' name='formDoor[]' id='"+j+"' value= '' />"+pageName[j]+"<br />");
document.getElementById(j).value = pageLink[j];
}
</script>
<input type="submit" name="formSubmit" value="Submit" />
</form>
But in the other file, it says variables are undefined. seems like variables doesn't pass to the 'b.php' file
Can anyone please tell me how to do this?
Your current code for adding checkboxes would likely be executed before the search result arrives (i.e.: before hndlr is executed), so all arrays are still empty. The solution would be to move the checkbox creation code into the hndlr function.
Here's the fixed page.
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<form id="bform" action="b.php" method="post">
<input type="submit" name="formSubmit" value="Submit" />
</form>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
var f=document.getElementById('bform'), prev=f.children[0];
for (var i = 0; i < response.items.length; i++) {
var ele, item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
ele = document.createElement('BR');
f.insertBefore(ele, prev);
prev = ele;
ele = document.createTextNode(pageName[i]);
f.insertBefore(ele, prev);
prev = ele;
ele = document.createElement('INPUT');
ele.type = 'checkbox';
ele.name = 'formDoor[]';
ele.id = i;
ele.value = encodeURI(pageLink[i]);
f.insertBefore(ele, prev);
prev = ele;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>